On September 29, 2022, I encountered this problem when I was doing a weather search page. At first, I wanted to use the method of importing json files to get this. Some json files are not that accurate. If the geography used If the location is a certain county, the city code may not be obtained. You also need to write your own method to intercept the string for accessing the geographic location.
Here is a simple method, we can use the API of some map platforms (of course, when the network is required), to obtain the city code, such as Baidu map or Gaode map. Here I use Gaode map. In the article At the end, I will attach the original platform link. You need to apply for a key when using the API of Gaode Open Platform
Here I introduce two ways to get the city code:
1. By specific geographic location
2. Positioning by latitude and longitude coordinates
1. Obtain geocoding by specific geographic location
-
Geocoding API service address
The parameters represented by parameters include required parameters and optional parameters. All parameters are separated by the ampersand character (&). The following list enumerates these parameters and the rules for their use.
-
Return result parameter description
The format of the response result can be specified through the request parameter output, and the default is JSON.
The following is the return parameter description:
-
-
service example
https://restapi.amap.com/v3/geocode/geo?address=北京市朝阳区阜通东大街6号&output=XML&key=<用户的key>
2. Obtain geocoding by latitude and longitude
-
Reverse geocoding API service address
The parameters represented by parameters include required parameters and optional parameters. All parameters are separated by the ampersand character (&). The following list enumerates these parameters and the rules for their use.
-
request parameters
-
Return result parameter description
The format of the response result of inverse geocoding is specified by the request parameter output.
-
service example
https://restapi.amap.com/v3/geocode/regeo?output=xml&location=116.310003,39.991957&key=<用户的key>&radius=1000&extensions=all
Original platform link: Geo/Reverse Geocoding