def query_GoogleV3(name): print('Querying for location:', name) service = geopy.GoogleV3(domain='maps.google.fr', timeout=5) loc = service.geocode(name, exactly_one=True) if loc is None: # extreme case, google doesn't return anything # try to split and query separate terms names = name.split() if len(names) == 1: raise NameError(name, 'Could not get any result from google API') else: loc = service.geocode(names[0], exactly_one=True) address_dict = loc.raw['address_components'] print(address_dict) d = dict() d['admin_lvl1'] = '' d['admin_lvl2'] = '' d['locality'] = '' d['colloquial'] = '' d['country'] = '' # first pass for component in address_dict: print(component['long_name'], ' ## ', component['types']) if u'administrative_area_level_2' in component['types']: d['admin_lvl2'] = component['long_name'] elif u'colloquial_area' in component[ 'types']: # sometimes contains region name instead of lvl1 d['colloquial'] = component['long_name'] elif u'administrative_area_level_1' in component['types']: d['admin_lvl1'] = component['long_name'] elif u'country' in component['types']: d['country'] = component['long_name'] elif u'locality' in component['types']: d['locality'] = component['long_name'] return d
def query_GoogleV3(name): print('Querying for location:', name) service = geopy.GoogleV3(domain='maps.google.fr', timeout=5) loc = service.geocode(name, exactly_one=True) address_dict = loc.raw['address_components'] print(address_dict) d = dict() d['admin_lvl1'] = '' d['admin_lvl2'] = '' d['locality'] = '' d['colloquial'] = '' d['country'] = '' # first pass for component in address_dict: print(component['long_name'], ' ## ', component['types']) if u'administrative_area_level_2' in component['types']: d['admin_lvl2'] = component['long_name'] elif u'colloquial_area' in component['types']: # sometimes contains region name instead of lvl1 d['colloquial'] = component['long_name'] elif u'administrative_area_level_1' in component['types']: d['admin_lvl1'] = component['long_name'] elif u'country' in component['types']: d['country'] = component['long_name'] elif u'locality' in component['types']: d['locality'] = component['long_name'] return d
def get_goog_geolocator(geocode_api_key): """ Get the geopy geolocator object, setup with goog auth. """ ctx = ssl.create_default_context(cafile=certifi.where()) geopy.geocoders.options.default_ssl_context = ctx geolocator = geopy.GoogleV3(user_agent='where should I live next', api_key=geocode_api_key, timeout=3) return geolocator
def get_full_adr(adr): coder = geopy.GoogleV3(API_KEY) raw = coder.geocode(adr, exactly_one=True).raw print(raw) num = raw["address_components"][0]["long_name"] street = raw["address_components"][1]["long_name"] plz = raw["address_components"][-1]["long_name"] ort = raw["address_components"][2]["long_name"] return street, num, ort, plz
def geolocator(self): if self.source == 'openstreet': geolocator = geopy.geocoders.Nominatim(user_agent='homeservice') elif self.source == 'gmaps': geolocator = geopy.GoogleV3(api_key=self.token) else: raise ValueError return geolocator
def get_adr(lat, long): coder = geopy.GoogleV3(API_KEY) raw = coder.reverse([lat, long], exactly_one=True).raw print(raw) num = raw["address_components"][0]["long_name"] street = raw["address_components"][1]["long_name"] plz = raw["address_components"][-1]["long_name"] ort = raw["address_components"][2]["long_name"] return street, num, ort, plz
def _get_geolocator(self): """ Only create the geolocator if needed Returns ------- geopy.geolocator """ if not hasattr(self, 'geolocator'): self.geolocator = geopy.GoogleV3() return self.geolocator
def get_nearby_places(address, search_query=None): # places search api url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json' google_geo = geopy.GoogleV3() # TODO: check for exceptions location = google_geo.geocode(address) location = str(location.latitude) + ',' + str(location.longitude) params = dict(location=location, radius=RADIUS, key=environ['GOOGLE_KEY']) if search_query: params['type'] = search_query response = requests.get(url, params=params) return response.json()['results']
def get_timezone_from_address(address): geocode = geopy.GoogleV3().geocode location = geocode(address) timezone_url = 'https://maps.googleapis.com/maps/api/timezone/json' try: google_key = environ['GOOGLE_KEY'] except KeyError: exit('google_key.missing = Please set GOOGLE_KEY ' 'as an environment variable') response = requests.get( timezone_url, { 'location': '%s,%s' % (location.latitude, location.longitude), 'timestamp': time.time(), 'key': google_key, }) return timezone(response.json()['timeZoneId'])
def getTracksByPlaceGoogle(self, place, timeout=10, only_points=True): """ Gets the points of the specified place searching in Google's API. Parameters ---------- place: string Place to get the points timeout: int Time, in seconds, to wait for the geocoding service to respond before returning a None value. only_points: boolean True to retrieve only the points that cross a place. False to retrive all the points of the tracks that cross a place. Returns ------- place: DFTrack A DFTrack with the points of the specified place or None if anything is found. """ try: geolocator = geopy.GoogleV3() location = geolocator.geocode(place, timeout=timeout) except geopy.exc.GeopyError as geo_error: return None southwest_lat = float( location.raw['geometry']['bounds']['southwest']['lat']) northeast_lat = float( location.raw['geometry']['bounds']['northeast']['lat']) southwest_lng = float( location.raw['geometry']['bounds']['southwest']['lng']) northeast_lng = float( location.raw['geometry']['bounds']['northeast']['lng']) df_place = self.df[(self.df['Latitude'] < northeast_lat) & (self.df['Longitude'] < northeast_lng) & (self.df['Latitude'] > southwest_lat) & (self.df['Longitude'] > southwest_lng)] if only_points: return self.__class__(df_place) track_list = df_place['CodeRoute'].unique().tolist() return self.__class__(self.df[self.df['CodeRoute'].isin(track_list)])
def __init__(self, data_folder="data", terms_folder="terms"): self.cache = shelve.open(os.path.join(data_folder, "cache.db")) self.terms_db = TermsDB(terms_folder) # Coords limits for geolocation # bot left top right self.limits = (-47, -24.05, -46.30, -23.35) self.regions = None self.osm = geopy.Nominatim(view_box=self.limits) self.gm = geopy.GoogleV3() self.server_options = { "osm": self.geocode_osm, "gm": self.geocode_gm, } self.shapefy_regions( os.path.join(data_folder, "subprefeituras.geojson"))
def geomap(address, search_query, target_folder=None): if not address.strip(): return [] search_query = search_query.strip() searches = get_nearby_places(address, search_query) transit = get_nearby_transit(address) schools = get_nearby_schools(address) google_geo = geopy.GoogleV3() # get lat/lng of given address coordinates = google_geo.geocode(address) building_descr = ("Queried Building", "red", 20) searches_descr = ("Nearby " + search_query, "green", 10) transit_descr = ("Nearby bus or subway", "blue", 10) school_descr = ("Nearby School", "yellow", 10) building = dict(description=building_descr[0], latitude=coordinates.latitude, longitude=coordinates.longitude, color=building_descr[1], radius=building_descr[2]) points_list = [building] add_to_csv(searches, searches_descr, points_list) add_to_csv(transit, transit_descr, points_list) add_to_csv(schools, school_descr, points_list) if target_folder: path = join(target_folder, 'search.csv') with open(path, 'w') as csvfile: columns = ('description', 'latitude', 'longitude', 'FillColor', 'radius_in_pixels') writer = csv.writer(csvfile) writer.writerow(columns) writer.writerows([(row['description'], row['latitude'], row['longitude'], row['color'], row['radius']) for row in points_list]) # required print statement for crosscompute # (http://crosscompute.com/docs) print('coordinates_geotable_path = ' + path) building = dict(latitude=building['latitude'], longitude=building['longitude']) return dict(address=building, points=points_list)
def geocoding(onePgAdrsList): #[(name, address, province, zip,(100,100)),(),()] global rowCount googlev3 = geopy.GoogleV3() geoAdrsList = [] for el in onePgAdrsList: adrsCnt = '' newItem = [] gps = tuple() for i in range(1,4): adrsCnt += (el[i]+' ') rowCount += 1 try: place,gps = googlev3.geocode(adrsCnt) except Exception as err: print ("on row: "+str(rowCount)+". Cannot find Geolation for: "+adrsCnt+" ziplist[0] is: "+str(zipList[0])) for item in el: newItem.append(item) newItem.append(gps) geoAdrsList.append(newItem) return geoAdrsList
import geopy import geotable import numpy as np from geotable.projections import get_transform_shapely_geometry from invisibleroads_macros.disk import make_unique_folder, uncompress from os.path import exists, join, splitext from shapely.geometry import Point from urllib.request import urlretrieve geometry_columns = ['geometry_layer', 'geometry_proj4', 'geometry_object'] target_folder = make_unique_folder('/tmp') g = geopy.GoogleV3('AIzaSyDNqc0tWzXHx_wIp1w75-XTcCk4BSphB5w').geocode location = g('Greensboro, NC') p = Point(location.longitude, location.latitude) proj4s = open('proj4s.txt').read().splitlines() target_proj4 = geotable.LONGITUDE_LATITUDE_PROJ4 archive_url = ('https://egriddata.org/sites/default/files/' 'GSO_RNM_GIS_Network.zip') archive_path = '/tmp/greensboro-synthetic-network.zip' archive_folder = splitext(archive_path)[0] if not exists(archive_path): urlretrieve(archive_url, archive_path) if not exists(archive_folder): archive_folder = uncompress(archive_path) source_folder = join(archive_folder, 'GSO_RNM_GIS_Network', 'Rural') source_path = join(source_folder, 'Line_N.shp') t = line_table = geotable.load(source_path)
from geopy.distance import vincenty wikimapia_api_key = "YOURWIKIMAPIAAPIKEYHERE" ap = argparse.ArgumentParser() ap.add_argument("-c", "--city", required=True, help="Pass in a city name like: Aurora Colorado") args = vars(ap.parse_args()) print "[*] Attempting to resolve %s" % args['city'] # find the location geosearch = geopy.GoogleV3() geo_result = geosearch.geocode(args['city']) # if we receive a result extract the coordinates if geo_result is not None: latitude = geo_result.latitude longitude = geo_result.longitude # send off a request to Wikimapia to get the city url = "http://api.wikimapia.org/?key=%s&function=place.getnearest&lat=%f&lon=%f&format=json&count=1&category=88" % ( wikimapia_api_key, latitude, longitude) response = requests.get(url) if response.status_code == 200:
#a= [(1,2,3),"122",121] #b= [(1,2,3),"12",121] #c= [[(1,2,3),"122",121]] #if b not in c: #print("hahaha") #if a in c: #print("yes") #def show_time(time): #hours = time//3600 #minutes = (time//60)%60 #seconds = time%60 #print ("program runs for "+str(int(hours))+" hours, "+str(int(minutes))+" minutes, "+str(seconds)+" seconds.") #show_time(1445121.74545841454) #a=9 #import time #time.#b=5 ##c=a%b ##print (c) #a= "123" #b= str(a) #print(b) import geopy googlev3 = geopy.GoogleV3() place,gps = googlev3.geocode(" Indian Falls Road Corfu NY 14036") print (gps)
import json import re import geopy import os API_KEY = os.environ["GOOGLE_API_KEY"] geocoder = geopy.GoogleV3(api_key=API_KEY) projects = [] with open("data/projects.json") as f: projects = json.load(f) print "Loaded projects" for p in projects: title = p["title"] address = None if re.match("\d+ \w", title): address = title else: match = re.search("\((\d+.+)\)", title) if match: address = match.group(1) if address: p["address"] = address print "Geocoding: " + address location = geocoder.geocode(address + ", Mountain View, CA") if location: p["location"] = (location.latitude, location.longitude) else: print "Error geocoding: " + address
from geopy.distance import vincenty wikimapia_api_key = "C7820673-5EA3C999-8466B6BE-D88E4218-4BC9FD76-9D3FECDE-835F2457-4EB2AEB7" ap = argparse.ArgumentParser() ap.add_argument("-c", "--city", required=True, help="Pass in a city name like: Tulsa Oklahoma") args = vars(ap.parse_args()) print("[*] Attempting to resolve %s" % args['city']) #find the lcoation geosearch = geopy.GoogleV3(api_key="AIzaSyDGmKWqcPwiz2YAgpAh0iG-RcsLko6t-7o") geo_result = geosearch.geocode(args['city']) if geo_result is not None: latitude = geo_result.latitude longitude = geo_result.longitude url = "http://api.wikimapia.org/?key=%s&function=place.getnearest&lat=%f&lon=%f&format=json&count=1&category=88" % ( wikimapia_api_key, latitude, longitude) response = requests.get(url) if response.status_code == 200: nearest = json.loads(response.content)
import geopy import itertools from geopy.distance import vincenty helper = "winnipeg manitoba" locations = {} locations["333 portage ave"] = [] locations["329 hargrave st"] = [] locations["main street and pioneer ave"] = [] # create a new Google geocoder geocoder = geopy.GoogleV3() # iterate over the locations for location in locations: # perform the geocoding locations[location] = geocoder.geocode("%s %s" % (location, helper)) # measure distance between each point for pairs in itertools.combinations(locations.keys(), r=2): location_1 = locations[pairs[0]].point location_2 = locations[pairs[1]].point distance = vincenty(location_1, location_2).meters print "%s => %s (%fm)" % (pairs[0], pairs[1], distance)
# <codecell> #dait = atdict.items() # <codecell> print listz[3] # <codecell> import geopy # <codecell> geo = geopy.GoogleV3() # <codecell> geo.geocode(listz[3]) # <codecell> olenz = len(listz) # <codecell> dachoice = random.randint(0, olenz) # <codecell>