Google maps places api python谷歌地圖API(獲取商戶信息)

google官方文檔 
GoogleMaps Geocoding API:https://developers.google.com/maps/documentation/geocoding/geocoding-strategies 
GoogleMaps Places API Web Service:https://developers.google.com/places/web-service/search?hl=zh-twpython

使用的python包: 
http://github.com/slimkrazy/python-google-places 
https://github.com/googlemaps/google-maps-services-pythongit

前提條件:你可以正常訪問Google!
若是不能正常訪問到google就想用GoogleMaps,那這就比較尷尬了,我也很無奈。github

1.準備工做
你得有個google帳號,打開https://console.developers.google.com/apis/credentials?project=imperial-palace-174906&authuser=0web

1.1建立google項目獲取項目祕鑰
若是還沒建立項目的話,那先建立個項目,我這裏是建立了一個googlemaps的項目 json

請記住3中圈中的祕鑰,咱們代碼中要使用到。api

1.2在項目中添加googleMaps服務:Google Maps Geocoding API,Google Places API Web Service
在剛剛建立的項目庫中,添加googleMaps的Google Maps Geocoding API和Google Places API Web Service app

(因爲我已經添加了,因此列表中是沒有顯示的)python2.7

1.3而後在信息中心就能夠看到你剛纔添加的兩個maps服務函數

上面的圖片是最近是用項目祕鑰請求這個maps服務的一些圖標post

2.安裝python所需的包(我使用的是python2.7.12版本)
兩個包分別是: 
http://github.com/slimkrazy/python-google-places (警示:這個包存在一個嚴重的bug,詳情:http://blog.csdn.net/dongyouyuan/article/details/77169560) 
pip安裝:pip install python-google-places 
https://github.com/googlemaps/google-maps-services-python 
pip安裝:pip install -U googlemaps 
你會發現googlemaps中也有python-google-places中的功能,想問我爲毛還用一個第三方的包,然而我真的無言以對,鬼知道我當初爲何用這個包。0.0(我當時搜google maps places api python 第一個就是 http://github.com/slimkrazy/python-google-places就用了)後面看有沒有時間,對比一下這包和google官方包的區別 
————-2017-08-04補充———————————————————————————————————– 
看了一下googlemaps中的python-google-places的功能,發現其返回地點的內容實在是少,只有寥寥無幾的幾個字段。 http://github.com/slimkrazy/python-google-places中詳細程度真的是很厲害。所用用它是沒錯的

{
            "rating": 5, 
            "name": "STR Analytics", 
            "reference": "CmRRAAAAEyrq32Ve7RKLtI6CWpaAoTFrR2yVWlKTfnbNTmCRLj3yXcIs2k6H45JPPwPZyIpMPxEBfVIqdD9BTWekJliAvgX_OH-FJyYUWnso9oZ2CjN97I2GWhXTSK1TBUo3HBVxEhDRxa-R4nxh8UqHeJPi9LHtGhQ6VMxxTnuXCwm9vZgY0IcnTaqQhg", 
            "geometry": {
                "location": {
                    "lat": 39.9148173, 
                    "lng": -105.1206877
                }, 
                "viewport": {
                    "northeast": {
                        "lat": 39.9158015802915, 
                        "lng": -105.1193284197085
                    }, 
                    "southwest": {
                        "lat": 39.9131036197085, 
                        "lng": -105.1220263802915
                    }
                }
            }, 
            "place_id": "ChIJ1VlFO-Tta4cRGQHpjODHvXU", 
            "formatted_address": "11001 W 120th Ave, Broomfield, CO 80021, United States", 
            "id": "b0003b168c40b2d378933f440b7f9a4116187dc5", 
            "types": [
                "point_of_interest", 
                "establishment"
            ], 
            "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png"
        },
—————2017-08-04補充完畢————————————————————————————————————

3.簡單粗暴的代碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Author: Dongyouyuan
# @Software: PyCharm
# @File: googleMap.py
# @Time: 17-8-2 上午11:31

from googleplaces import GooglePlaces
import googlemaps

import sys

reload(sys)
sys.setdefaultencoding('utf8')

class GoogleMaps(object):
    """提供google maps服務"""

    def __init__(self):

        self._GOOGLE_MAPS_KEY = "你的祕鑰"
        self._Google_Places = GooglePlaces(self._GOOGLE_MAPS_KEY)
        self._Google_Geocod = googlemaps.Client(key=self._GOOGLE_MAPS_KEY)

    def _text_search(self, query, language=None, location=None):
        """
        根據搜索字符串,請求google API傳回推薦的列表
        :param query: 搜索字符串
        :param language: 語言
        :param location: 地區篩選
        :return:
        """
        # lat_lng = {"lat": "22.5745761", "lng": "113.9393772"}
        # 經緯度附近搜索
        # text_query_result = self.self._Google_Places.text_search(query='Gong Yuan', lat_lng=lat_lng)
        # location 爲人可認識的名稱
        # text_query_result = self.self._Google_Places.text_search(query='Tang Lang Shan', location='shenzhen')
        # 指定語言搜索
        text_query_result = self._Google_Places.text_search(query=query, language=language, location=location)
        return text_query_result.places

    def _reverse_geocode(self, lat, lng, language=None):
        """
        根據經緯度請求google API獲取座標信息,返回信息
        :param lat: 緯度
        :param lng:經度
        :param language:語言
        :return:
        """
        # 根據經緯度獲取地址信息 pincode
        list_reverse_geocode_result = self._Google_Geocod.reverse_geocode((lat, lng), language=language)
        # print json.dumps(list_reverse_geocode_result, indent=4)
        return list_reverse_geocode_result

    def _return_reverse_geocode_info(self, lat, lng, language=None):
        """
        整理信息
        :param lat:緯度
        :param lng:經度
        :param language:語言
        :return:
        """
        list_reverse_geocode = self._reverse_geocode(lat, lng, language=language)
        if list_reverse_geocode:
            city = ''
            pincode = ''
            route = ''
            neighborhood = ''
            sublocality = ''
            administrative_area_level_1 = ''
            country = ''
            street_number = ''
            # 全名地址
            formatted_address = list_reverse_geocode[0]['formatted_address']
            for address_info in list_reverse_geocode[0]['address_components']:
                # 城市標識爲locality
                if 'locality' in address_info['types']:
                    city = address_info['long_name']
                # 郵政編碼標識爲postal_code
                elif 'postal_code' in address_info['types']:
                    pincode = address_info['long_name']
                # 街道路
                elif 'route' in address_info['types']:
                    route = address_info['long_name']
                # 類似地址名
                elif 'neighborhood' in address_info['types']:
                    neighborhood = address_info['long_name']
                # 地區名
                elif 'sublocality' in address_info['types']:
                    sublocality = address_info['long_name']
                # 省份
                elif 'administrative_area_level_1' in address_info['types']:
                    administrative_area_level_1 = address_info['long_name']
                # 國家
                elif 'country' in address_info['types']:
                    country = address_info['long_name']
                # 門牌號
                elif 'street_number' in address_info['types']:
                    street_number = address_info['long_name']
            return {'city': city, 'pincode': pincode, 'route': route, 'neighborhood': neighborhood,
                    'sublocality': sublocality, 'administrative_area_level_1': administrative_area_level_1,
                    'country': country, 'formatted_address': formatted_address, 'street_number': street_number}
        else:
            return None

    def get_pincode_city(self, lat, lng, language=None):
        """
        根據經緯度獲取該地區詳細信息
        :param lat: 緯度
        :param lng: 經度
        :return:
        """
        reverse_geocode_info = self._return_reverse_geocode_info(lat, lng, language=language)
        if reverse_geocode_info:
            return {'city': reverse_geocode_info['city'], 'pincode': reverse_geocode_info['pincode']}
        else:
            return None

    def get_address_recommendation(self, query, language=None, location=None):
        """
        獲取輸入地址的推薦地址(最多返回5個)
        :param query: 搜索地址名稱
        :param language: 語言
        :param location: 地區篩選
        :return:
        """
        return_size = 5
        list_return_info = list()
        list_places_text_search_result = self._text_search(query=query, language=language, location=location)
        # 默認返回5條數據
        if len(list_places_text_search_result) > return_size:
            list_places_text_search_result = list_places_text_search_result[:return_size]
        for place in list_places_text_search_result:
            result_geocode = self._return_reverse_geocode_info(place.geo_location['lat'], place.geo_location['lng'], language=language)
            # 數據不爲空
            if result_geocode:
                # 地點全路徑加上地點名
                result_geocode['formatted_address'] = '{} {}'.format(place.name, result_geocode['formatted_address'])
                result_geocode['place_name'] = place.name
                # 經緯度
                result_geocode['lat'] = '{}'.format(place.geo_location['lat'])
                result_geocode['lng'] = '{}'.format(place.geo_location['lng'])
                list_return_info.append(result_geocode)
        return list_return_info

if __name__ == '__main__':     # 使用實例     import json     google_maps = GoogleMaps()     result_recommendation_list = google_maps.get_address_recommendation(query='天河公園', language='zh', location='中國')     pincode_city = google_maps.get_pincode_city(22.547143, 114.062753)     print json.dumps(result_recommendation_list, indent=4, encoding='utf-8')     print '*'*100     print pincode_city 4.輸出結果 {     "code": 0,     "data": {         "address_recommendation": [             {                 "administrative_area_level_1": "廣東省",                 "city": "廣州市",                 "country": "中國",                 "formatted_address": "天河公園 中國廣東省廣州市天河區天河公園華翠街66號",                 "lat": "23.1267447",                 "lng": "113.3679628",                 "neighborhood": "天河公園",                 "pincode": "",                 "place_name": "天河公園",                 "route": "華翠街",                 "street_number": "66",                 "sublocality": "天河區"             },             {                 "administrative_area_level_1": "廣東省",                 "city": "廣州市",                 "country": "中國",                 "formatted_address": "天河公園(東門) 中國廣東省廣州市天河區天河公園華翠街66號",                 "lat": "23.12583799999999",                 "lng": "113.368506",                 "neighborhood": "天河公園",                 "pincode": "",                 "place_name": "天河公園(東門)",                 "route": "華翠街",                 "street_number": "66",                 "sublocality": "天河區"             },             {                 "administrative_area_level_1": "廣東省",                 "city": "廣州市",                 "country": "中國",                 "formatted_address": "天河公園(西門) 中國廣東省廣州市天河區天河公園天府路139號",                 "lat": "23.128752",                 "lng": "113.363186",                 "neighborhood": "天河公園",                 "pincode": "",                 "place_name": "天河公園(西門)",                 "route": "天府路",                 "street_number": "139",                 "sublocality": "天河區"             },             {                 "administrative_area_level_1": "廣東省",                 "city": "廣州市",                 "country": "中國",                 "formatted_address": "天河公園(南1門) 中國廣東省廣州市天河區天河公園黃埔大道中199號",                 "lat": "23.12312",                 "lng": "113.365254",                 "neighborhood": "天河公園",                 "pincode": "",                 "place_name": "天河公園(南1門)",                 "route": "黃埔大道中",                 "street_number": "199",                 "sublocality": "天河區"             },             {                 "administrative_area_level_1": "廣東省",                 "city": "廣州市",                 "country": "中國",                 "formatted_address": "天河公園(北1門) 中國廣東省廣州市天河區天河公園中山大道西246號-540號 郵政編碼: 510640",                 "lat": "23.131274",                 "lng": "113.367319",                 "neighborhood": "天河公園",                 "pincode": "510640",                 "place_name": "天河公園(北1門)",                 "route": "中山大道西",                 "street_number": "246號-540號",                 "sublocality": "天河區"             }         ]     },     "msg": "ok" } **************************************************************************************************** {'city': u'Shenzhen Shi', 'pincode': u'518000'} 5.代碼解析 以上代碼已經有很清晰的註釋了,可是我仍是要簡單明瞭的說一下吧。 GoogleMaps類提供兩個對外服務的方法:  get_address_recommendation:根據用戶的搜索字符和地區過濾,得到最多5條的返回結果,值得一提的是該函數的參數language是控制返回結果的語言,也就是說,你能夠搜query是park,location=’America’,language=’zh’,  get_pincode_city:根據經緯度獲取該地區的郵政編碼和城市名稱(我作了截取,只截取了城市和郵政編碼,事實上能夠獲取該地區的全部詳細信息,你能夠打印get_pincode_city方法裏面的reverse_geocode_info變量,你會有驚喜的發現) ---------------------  做者:DHogan  來源:CSDN  原文:https://blog.csdn.net/dongyouyuan/article/details/76618442  版權聲明:本文爲博主原創文章,轉載請附上博文連接!

相關文章
相關標籤/搜索