In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to use Python to achieve the conversion between geographical location and latitude and longitude coordinates, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
Latitude and longitude coordinates need to be provided when making map visualization, but generally speaking, what we usually get is only geographical location. For example, Goubuli steamed stuffed bun shop, 302 East Street, Beijing, needs latitude and longitude coordinate transformation before visualization.
If there are only a few data that need to be converted, you can manually convert them directly with Google Maps with its own longitude and latitude query, but the amount of data that needs to be converted in the real scene may be hundreds or even thousands, and then manual will be a headache.
How to convert geographic location into latitude and longitude coordinates in batch? In order to solve this problem, two methods to implement it with Python are introduced.
1. Call the third party API
The most common way is to call third-party API, such as Baidu, Amap and other service platforms, to provide corresponding functional interfaces, their technology is very mature, accurate and stable, the key is free ~, this tutorial takes Baidu as an example (the usage of Gao de is similar), introduce its usage
1.1. Log in to Baidu Map console with Baidu account.
Baidu Map Open platform
Create an application and get the AK parameters
After logging in to the console, select Application Management-> my applications-> create applications on the left.
There are three pieces of information to fill in in the create application page.
Application name, which can be filled in at will without restriction.
Application type, select server
IP whitelist is only a simple test for individuals. If you consider security, you can enter your own IP. If the AK parameter is leaked, the IP cannot be accessed without native IP, so you don't have to worry about the quota being embezzled by other users.
1.3, geocoding, inverse geocoding
Latitude and longitude geographic locations are divided into two categories according to the direction of transformation, and then we will demonstrate their usage respectively:
Geocoding: converting geographic addresses to coordinate points (latitude and longitude)
Reverse geocoding to convert latitude and longitude into geographic address
1.3.1 Geocoding
The following is the Python test code block, which combines the AK parameters (previously applied) and the geographic location you need to convert into the official url, which can be accessed with requests.
Import requests import json import re AK = 'your AK' address =' 10 Shangdi Street, Haidian District, Beijing 'url =' http://api.map.baidu.com/geocoding/v3/?address={}&output=json&ak={}&callback=showLocation'.format(address,AK) res = requests.get (url) print (res.text) results = json.loads (re.findall (r'\ ((. *)\), res.text) [0]) print ('\ n') print ('location is') Results ['result'] [' location'])
The output is as follows
ShowLocation&&showLocation ({"status": 0, "result": {"location": {"lng": 116.3084202915042, "lat": 40.05703033345938}, "precise": 1, "confidence": 80, "comprehension": 100, "level": "door address"}}) location is {'lng': 116.3084202915042,' lat': 40.0570303033345938}
1.3.2 inverse geocoding
Reverse geocoding is similar to geocoding.
Lat = '40.05703033345938' lng = '116.3084202915042' AK = 'your AK' url =' http://api.map.baidu.com/reverse_geocoding/v3/?ak={}&output=json&coordtype=wgs84ll&location={},{}'.format(AK,lat,lng) res = requests.get (url) print (res.text) address = json.loads (res.text) ['result'] [' formatted_address'] print ('\ n') print ('address is', address)
Free (bai) piao users like ours can call up to 6000 times a day with Baidu API, which basically meets our daily needs, but if this number is not enough for you, you can buy a higher usage quota online.
2,Geopy
2.1 introduction to Geopy Library
This paper introduces a Python package Geopy, which can also be used to convert latitude and longitude.
In fact, the latitude and longitude conversion principle of this package is based on the third-party API platform, because there are many third-party platforms for latitude and longitude conversion in the market. for convenience, Geopy encapsulates these interfaces in a class and calls them with the help of Geopy module. The third platforms supported are as follows.
Geopy as a geo-processing package, in addition to the above geocoding, inverse geocoding functions, there is another function that makes me experience, providing two latitude and longitude coordinates to calculate their shortest distance on the earth.
Here's how to use Geopy.
2. 2 geocoding
When using geocoding function, you need to use the geocoders module of Geopy, and Geopy encapsulates all third-party API into geocoders
Here we choose the Nominatim geoencoder provided on the OpenStreetMap platform, because it can be used for us free of charge, and there is no need to apply for API, but the disadvantage is current limit, limit, and can not be accessed frequently on a large scale, otherwise a 403429 error code will be returned.
From geopy.geocoders import Nominatim geolocator=Nominatim () location= geolocator.geocode ("Xierqi Bei Lu, Haidian District, Beijing") print (location.address) print (location.latitude,location.longitude)
The results are as follows
Xierqi North Road, Dongbei Wangcun, Haidian District, Beijing, 102208, China 40.056793 116.305811
2.3 inverse geocoding
From geopy.geocoders import Nominatim geolocator=Nominatim () location= geolocator.reverse ("40.056793 116.305811") print (location.address)
The results are as follows
1Qing, Xierqi North Road, Dongbei Wangcun, Haidian District, Beijing, 102208, China
The result looks good, simple and convenient, but as mentioned earlier, the Nominatim module is limited, so don't visit it frequently, or the following error will occur
2.4 calculate distance based on longitude and latitude
What surprises me most about Geopy is this usage, which provides two latitude and longitude coordinates to calculate the distance between them. Because the earth is specifically an ellipse, it cannot be calculated according to the conventional method. At present, there are several popular models
Model major (km) minor (km) flattening 'WGS-84': (6378.137, 6356.7523142, 1 / 298.257223563),' GRS-80': (6378.137, 6356.7523141, 1 / 298.257222101), 'Airy (1830)': (6377.563396, 6356.256909, 1 / 299.3249646), 'Intl 1924: (6378.388, 6356.911946) 1 / 297.0), 'Clarke (1880)': (6378.249145, 6356.51486955, 1 / 293.465), GRS-67': (6378.1600, 6356.774719, 1 / 298.25),}
According to the official introduction, the official website chooses the WGS-84 model, and the final distance error calculated according to statistics is about 0.5%. The usage is as follows.
From geopy import distance newport_ri = (41.49008,-71.312796) cleveland_oh = (41.499498,-81.695391) print (distance.distance (newport_ri, cleveland_oh). Coordinate) # finally output in miles # output 538.39044536 wellington = (- 41.32,5.50) salamanca = (40.96,5.50) print (distance.distance (wellington, salamanca). Km) # output in km 19959.67926743 batch address coordinate translation
After talking about so many knowledge points above, let's introduce a case to review it briefly. In this case, we use Baidu API to realize the geographic location coordinate transformation, and convert all the address location data in a csv table into longitude and latitude in batches.
3.1 data reading
Import pandas as pd import string data_path = 'HRAUGUAGUP _ data _ df _ mapping _ location. CSV' df = pd.read_csv (data_path,encoding='GB18030') df
There are 98 pieces of data, each of which represents a geographical location; there are obviously some disturbing items in the data, such as the numeric characters at the left end and the delimiter\ t in the data; therefore, the data needs to be preprocessed before conversion.
3.2 data preprocessing
Def process_str (x): # data preprocessing to remove the preceding numbers and strings from\ t x = str (x) .replace ('\ t records last month') x = str (x) .strip (string.digits) return x df ['location'] = df [' location'] .apply (process_str) df
The pretreatment results are as follows
3.3 Geocoding (latitude and longitude conversion)
Import time start = time.time () AK = 'your AK' def get_location (str1): # get the latitude and longitude coordinates url =' http://api.map.baidu.com/geocoding/v3/?address={}&output=json&ak={}&callback=showLocation'.format(str1,AK) res = requests.get (url) results = json.loads (re.findall (r'\ ((. *?)\)' Res.text) [0]) return (results ['result'] [' location'] ['lat'], results [' result'] ['location'] [' lng']) df ['(lat,lng)'] = df ['location'] .apply (get_location) print (' time-consuming {} s'.format (time.time ()-start)) print (df)
In order to test the conversion efficiency, I have added a timer here; it takes about 4.65s to convert 98 pieces of data successfully, which is not bad, which is much better than Geopy.
3.5 case source data
I have packaged the data of the code used in this case, and those who are interested can reply the keyword: 210418 in the background of the official account.
So much has been introduced above, and finally a summary is made to talk about the respective advantages and disadvantages of the two methods in the transformation of geographical coordinates.
Third-party API
Advantages: geocoding and inverse coding are more accurate, high precision, and support high concurrency
Disadvantages: it does not support foreign countries, and the environment configuration is more complex.
Geopy (with Nominatim module)
Advantages: simple and convenient, quick to use; support foreign geocoding
Disadvantages: do not support concurrent access, low efficiency and low precision
Here is a suggestion: if the address data is in China, it is recommended to use a third-party API for longitude and latitude conversion, which is stable and accurate; if it involves lower latitude distance calculation, unit conversion or address data abroad, it is recommended to use Geopy.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.