def convert_geocoding(lat, lng): gm = Client(key=API_KEY) revGeo = gm.reverse_geocode( (lat, lng) ) # reverse_geocode func in googlemaps return list of reverse geocoding results return revGeo[0][ "formatted_address"] # retrieve information from the list returned
def get_CA_census(self, postcode, city, location, ip): gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY) results = gmaps.reverse_geocode( (location['latitude'], location['longitude'])) for r in results[0]['address_components']: try: types = r['types'] if types[0] == 'locality' and types[1] == 'political': city = r['long_name'] if city == 'Mississauga': city = 'Toronto' if types[0] == 'postal_code': postcode = r['long_name'] except: pass # first try from IPStore, else lookup census database and update the # ipstore in the process census, ipstore = self.get_from_ipstore(ip, postcode) if not census: census = CaCensus(city=city).get_profile() ipstore.census = census ipstore.geocode = results ipstore.geocoded_postal_code = postcode ipstore.save() # IPStore.objects.create( # ip=ip, # census=census, # geocode=results, # geocoded_postal_code=postcode # ) return census
def get_zipcode(lat, long): api_key = "API_KEY" while True: try: gmaps = Client(key=api_key) destination = gmaps.reverse_geocode((lat, long)) formatted_address = destination[0]['formatted_address'].split(",") zipcode = formatted_address[2].split(" ")[2] # geolocator = Nominatim() # loc = lat + "," + long # zipcode = geolocator.reverse(loc).raw['address']['postcode'] return zipcode except Exception as e: custom_sleep(4)
def update_gecode(ip, location): from googlemaps import Client # from django.conf import settings import json ip.latitude = location['latitude'] ip.longitude = location['longitude'] gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY) result = gmaps.reverse_geocode( (location['latitude'], location['longitude'])) ip.geocode = json.dumps(result) print result ip.save()
def reverse_geocode_ipstore(self, queryset): """Reverse geocode the new ip to get more info from lat/longs Args: queryset (TYPE): Description Returns: TYPE: Description """ from apps.warehouse.models import IPStore from googlemaps import Client from django.conf import settings import json gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY) import datetime _now = datetime.datetime.now() for ip in IPStore.objects.filter(geocode__isnull=True): print '---' print ip.ip print '---' qs = queryset.filter( meta__at_ip=ip.ip).order_by('-added_on') print qs print '---' if qs.count() > 0: obj = qs[0] else: obj = None if obj: location = obj.meta['ip2geo']['location'] ip.latitude = location['latitude'] ip.longitude = location['longitude'] result = gmaps.reverse_geocode((location['latitude'], location['longitude'])) ip.geocode = result ip.save() print '---' print ip.ip print '---' print location print '---' print ip.geocode print '---'
def update_gecode(self, ip, location): from googlemaps import Client from googlemaps.exceptions import Timeout from django.conf import settings import json ip.latitude = location['latitude'] ip.longitude = location['longitude'] try: gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY) result = gmaps.reverse_geocode( (location['latitude'], location['longitude'])) ip.geocode = result except Timeout: print 'unable to reverse geocode: %s' % (ip) ip.save()
class LocationService(object): """Class used to request geolocation info.""" def __init__(self): """Initiates the geolocation client.""" self.service = Client(key=GEO_LOCATION_API_KEY) def get_location_details(self, latitude, longitude): """Get location details by using latitude and longitude. This parses the location information to only get the required data. It also verifies if the location service is enabled to request details for it. :param latitude: Place's latitude :param longitude: Place's longitude :returns: It gets the parsed data from the location service when it's enabled otherwise get from a sample data """ if GEO_LOCATION_SERVICE_ENABLED: location_info = self.service.reverse_geocode((latitude, longitude)) else: location_info = sample return self.parse_location_info(location_info) def parse_location_info(self, location_info): """Parse the location information to get the expected fields. :param location_info: The location information provided by the location service :returns: The parsed data with only required fields """ info = location_info[0] return { "latitude": str(info['geometry']['location']['lat']), "longitude": str(info['geometry']['location']['lng']), "address": info['address_components'][1]['long_name'], "number": info['address_components'][0]['long_name'], "neighborhood": info['address_components'][2]['long_name'], "city": info['address_components'][3]['long_name'], "postal_code": info['address_components'][6]['long_name'], "state": info['address_components'][4]['short_name'], "country": info['address_components'][5]['long_name'] }
def google_maps_request(addr, key): gmaps = Client(key=key) # Geocoding an address geocode_result = gmaps.geocode(addr) print('geocode_result={}'.format(geocode_result)) # Look up an address with reverse geocoding reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452)) print('reverse_geocode_result={}'.format(reverse_geocode_result)) # Request directions via public transit now = datetime.now() directions_result = gmaps.directions( origin="Sydney Town Hall", destination="Parramatta, NSW", mode="transit", departure_time=now ) print('directions_result={}'.format(directions_result))
# pip install googlemaps from googlemaps import Client from datetime import datetime api_key = 'your key' gmaps = Client(api_key) dir(gmaps) whitehouse = '1600 Pennsylvania Avenue, Washington, DC' whitehouse_geoloc = gmaps.geocode(whitehouse) print whitehouse_geoloc destination = gmaps.reverse_geocode((38.897096, -77.036545)) print destination now = datetime.now() directions_result = gmaps.directions("Sydney Town Hall", "Parramatta, NSW", mode="transit", departure_time=now) lat_long = (gmaps.geocode( '326 Perkins Library, Durham, NC 27708')[0]['geometry']['location']['lat'], gmaps.geocode('326 Perkins Library, Durham, NC 27708')[0] ['geometry']['location']['lng']) print lat_long duke = gmaps.reverse_geocode(lat_long)[0]['formatted_address'] print duke local = gmaps.places('restaurant near ' + duke) print local['results'][0]['formatted_address'] print local['results'][0]['name']
def get_info_from_coordinate(lat: float, lng: float, client: googlemaps.Client): return client.reverse_geocode((lat, lng))
# -*- coding: utf-8 -*- from googlemaps import Client from datetime import datetime from polyline.codec import PolylineCodec import json import math gmaps = Client(key='AIzaSyCoIFqQxNU-M9oF62wVj2Fj37wn-wgh1Cw') # Geocoding an address geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA') # Look up an address with reverse geocoding reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452)) # # Request directions via public transit # now = datetime.now() # directions_result = gmaps.directions((23.7846429,90.376789), # (23.775885, 90.723063), # mode="driving", # departure_time=now) now = datetime.now() directions_result = gmaps.directions( "ShewraPara Bus Stand, Begum Rokeya Ave, Dhaka 1216", "Mohakhali Bus Stop, Dhaka 1205", mode="driving", departure_time=now) now = datetime.now()
from googlemaps import Client apiKey = 'AIzaSyDgoY6l7wIw2ekbf2aYnCjUyYTKxFVG9p0' lat = input("Please enter latitude: ") lng = input("Please enter longitude: ") maps = Client(apiKey) reverseGeo = maps.reverse_geocode((lat,lng)) address = reverseGeo[0]['formatted_address'] print(address)
# Get profile print client.get_profile() # Find pokemon for pokemon in client.find_pokemon(bounds): print pokemon print pokemon.get_expires_timestamp() print time.time() id = pokemon.get_name() if id in notify: PST = timezone('US/Pacific') expires_time = pokemon.get_expires().replace(tzinfo=timezone('UTC')).astimezone(PST) address = gmaps.reverse_geocode((pokemon.get_location()["latitude"], pokemon.get_location()["longitude"]))[0]['address_components'] formatted_address = address[0]['short_name'] + ' ' + address[1]['short_name'] + ', ' + address[2]['short_name'] message = "%s at %s.\nExpires at %s:%02d:%02d (in %d:%02d)" % (pokemon.get_name(), formatted_address, expires_time.strftime("%-I"), expires_time.minute, expires_time.second, int(pokemon.sec_till_expire()/60), pokemon.sec_till_expire()%60) #mapslink = 'http://maps.apple.com/?q=%s&ll=%f,%f&z=18' % (pokemon.get_name(), pokemon.get_location()["latitude"], pokemon.get_location()["longitude"]) mapslink = 'http://maps.apple.com/?q=%f,%f&ll=%f,%f&z=18' % (pokemon.get_location()["latitude"], pokemon.get_location()["longitude"], pokemon.get_location()["latitude"], pokemon.get_location()["longitude"]) print mapslink if is_unique(pokemon, archive) and int(pokemon.sec_till_expire()/60) > 0: archive.append(pokemon) my_channel.push_note("Wild "+ pokemon.get_name().upper() + " appeared!", message + '\n' + mapslink) print "\nWild "+ pokemon.get_name().upper() + " appeared!\n", message + '\n' + mapslink
class TrafficInformation(object): """ """ def __init__(self): config_read = ConfigRead("config.ini") gmaps_conf = config_read.read_googlemaps_config() self.gmaps = Client(key=gmaps_conf["token"]) self.home = gmaps_conf["home"] self.work = gmaps_conf["work"] def current_address(self, gl_tuple): """ :return: """ adress_dict = dict() address_list = self.gmaps.reverse_geocode(gl_tuple) for addr_data in address_list[0]['address_components']: if addr_data['types'][0] == 'street_number': adress_dict['number'] = addr_data['long_name'] if addr_data['types'][0] == 'route': adress_dict['street'] = addr_data['long_name'] if addr_data['types'][0] == 'political': adress_dict['neibor'] = addr_data['long_name'] if addr_data['types'][0] == 'locality': adress_dict['city'] = addr_data['long_name'] if addr_data['types'][0] == 'country': adress_dict['country'] = addr_data['long_name'] if addr_data['types'][0] == 'postal_code': adress_dict['postal_code'] = addr_data['long_name'] return adress_dict def home_and_work_info(self, to_home=True): """ :param to_home: :return: """ info_dict = dict() if to_home: destination, departure = self.home, self.work else: destination, departure = self.work, self.home now = datetime.now() dt_info = self.gmaps.directions( departure, destination, mode='driving', departure_time=now ) info_dict['distance'] = dt_info[0]['legs'][0]['distance']['text'] info_dict['duration'] = dt_info[0]['legs'][0]['duration_in_traffic']['text'] return info_dict def time_to_somewhere(self, from_addr, to_addr): """ :param from_addr: :param to_addr: :return: """ now = datetime.now() info_dict = dict() dt_info = self.gmaps.directions( from_addr, to_addr, mode='driving', departure_time=now ) info_dict['distance'] = dt_info[0]['legs'][0]['distance']['text'] info_dict['duration'] = dt_info[0]['legs'][0]['duration_in_traffic']['text'] return info_dict
def get_census_data(self): """ Gets the census data against a given lookup Args: q (text): query string for text Returns: json: json for geo """ from apps.warehouse.models import IPStore from plugins.census.models import Geography from plugins.census.api import CensusUS from plugins.census.ca import CaCensus census = None if self.meta: # first we will lookup the existing ipstore if it has data # then we will lookup the respective geographic census tables try: ip = self.meta['ip'] except KeyError: ip = None try: warehouse = IPStore.objects.get(ip=ip) census = warehouse.census except IPStore.DoesNotExist: warehouse = IPStore.objects.create(ip=ip) if not census: try: ip2geo = self.meta['ip2geo'] except KeyError: ip2geo = None if ip and ip2geo: try: country = ip2geo['country']['iso_code'] except KeyError: country = None try: postcode = ip2geo['postal']['code'] except KeyError: postcode = None try: city = ip2geo['city']['names']['en'] except KeyError: city = None try: location = ip2geo['location'] except: location = None if country == 'US' and postcode: queryset = IPStore.objects.filter( geocoded_postal_code=postcode, census__isnull=False) if queryset.count(): census = queryset[0].census else: try: geoid = Geography.objects.get( full_name__contains=postcode ).full_geoid.replace('|', '00US') census = CensusUS( geoid=geoid).computed_profile() except Geography.DoesNotExist: print 'PostCode ID: %s' % (postcode) warehouse.census = census warehouse.save() if country == 'Canada' and location: from googlemaps import Client from django.conf import settings gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY) results = gmaps.reverse_geocode( (location['latitude'], location['longitude'])) return census
def main(): import argparse parser = argparse.ArgumentParser( prog="Geographical Coordinate to DataBase", description= "Converts and saves geographical coordinates from a CSV file to Database.", add_help=True, ) parser.add_argument( "-p", "--path-to-csv", dest="csv_file_path", help="Path to csv file containing geographical coordinates", required=True, ) parser.add_argument("-v", "--verbose", help="Activates debug log level.", action="store_true") parser.add_argument( "-o", "--output", help="Defines if logging should output on terminal.", action="store_true", ) parser.add_argument( "-k", "--google-maps-key", dest="api_key", help="API key to use googlemaps", required=True, ) logger.info(">>> Starting the Coordinate Converter.") args = parser.parse_args() if args.output: logger.debug("Showing logs on terminal.") root_logger = logging.getLogger() console_handler = logging.StreamHandler(os.sys.stdout) root_logger.addHandler(console_handler) if args.verbose: logger.info("Setting log level to DEBUG") logger.setLevel("DEBUG") logger.info("Checking CSV File.") if args.csv_file_path: check_path = Path(args.csv_file_path) if not check_path.exists(): message = "Path to csv not found." logger.critical(message) os.sys.exit(1) test_client = GoogleMapsClient(args.api_key) logger.info("Checking API Key.") try: test_client.reverse_geocode( (30.1084987, -51.3172284)) # Porto Alegre, RS except ApiError as e: logger.critical(e.message) os.sys.exit(1) else: logger.debug(f"API Key OK {args.api_key}") converter = Converter(api_key=args.api_key) dataset_from_csv = converter.get_coordinates_from_csv_file( args.csv_file_path) converter.save_dataset_coordinates_to_database(dataset_from_csv)
from googlemaps import Client lat = input('Enter latitude: ') lng = input('Enter longitude: ') gm = Client(key="AIzaSyCMw47C5XfGqpJD_WoB37sO6DwRyO3i5l4") rev_geo = gm.reverse_geocode((lat, lng)) print("Street address:", rev_geo[0]["formatted_address"]) print("Location name: ", rev_geo[0]['address_components'][0]['long_name'])
def getZipcodeGoogle(lat, lon): gkey = '' g = Client(key=gkey) location = g.reverse_geocode((lat,lon)) print(location)
class Converter: def __init__(self, api_key=None): self._api_key = api_key if not self._api_key: self._api_key = config("GOOGLE_MAPS_API_KEY") self.maps = GoogleMapsClient(key=self._api_key) logger.debug("Instantiating Converter") self.database = Database() @staticmethod def is_address_valid(address): """ Validates if an Address has complete information, if all address fields are filled with data. :param address: json containing all address components :return: bool """ address_components = [ "country", "state", "city", "neighborhood", "street_number", "street_name", "postal_code", "latitude", "longitude", ] address_keys = [*address.keys()] address_keys.sort() address_components.sort() if address_keys == address_components: return True return False @staticmethod def get_address_from_address_components(address_components): """ Extracts data from address components returned from a query in googlemaps reverse_geocode api :param address_components: a dict with address components :return: a dict with transformed address """ address = {} for component in address_components: component_types = component.get("types", "") if "country" in component_types: address.update({"country": component.get("long_name")}) if "administrative_area_level_1" in component_types: address.update({"state": component.get("short_name")}) if "administrative_area_level_2" in component_types: address.update({"city": component.get("long_name")}) if "sublocality_level_1" in component_types: address.update({"neighborhood": component.get("long_name")}) if "street_number" in component_types: address.update({"street_number": component.get("long_name")}) if "route" in component_types: address.update({"street_name": component.get("long_name")}) if "postal_code" in component_types: address.update({"postal_code": component.get("long_name")}) if address: return address @staticmethod def get_coordinates_from_csv_file(file_path, csv_columns=None): """ Read geographical coordinates from CSV file. If no specific columns are passed, id reads all columns from csv and the CSV file must have the following format: +------------+-----------+ | latitude, | longitude | <- headers | -30.896756,| 51.987642 | <- coordinates :param file_path: str :param csv_columns: list containing the header columns :return: """ csv_dataset = pd.read_csv(file_path, usecols=csv_columns) return csv_dataset def get_address_from_coordinates(self, latitude, longitude): """Converts a latitude, longitude address coordinate in a valid address :param latitude: float :param longitude: float :return: dict """ try: return self.maps.reverse_geocode( (latitude, longitude), result_type="street_address", location_type="ROOFTOP", ) except ApiError as e: logger.critical(e.message) os.sys.exit(1) def save_to_database(self, coordinate, address): coordinate_table = self.database.conn["coordinate_points"] addresses_table = self.database.conn["addresses"] try: coordinate_table.insert(coordinate) addresses_table.insert(address) message = f"Address saved to database: {address}" if __name__ != '__main__': print(message) logger.info(message) except IntegrityError as exc: message = str(exc.orig).replace("\n", " ") if __name__ != '__main__': print(message) logger.critical(message) except Exception as exc: if __name__ != '__main__': print(exc) logger.critical(exc) def save_dataset_coordinates_to_database(self, dataset_coordinates): for (number, coordinate) in dataset_coordinates.iterrows(): result = self.get_address_from_coordinates(coordinate["latitude"], coordinate["longitude"]) if result: address_components = result[0].get("address_components", "") if address_components: complete_address = self.get_address_from_address_components( address_components) if complete_address: complete_address.update({ "latitude": coordinate["latitude"], "longitude": coordinate["longitude"], }) if self.is_address_valid(complete_address): coordinate = { "latitude": coordinate["latitude"], "longitude": coordinate["longitude"], "distance_km": coordinate["distance_km"], "bearing_degrees": coordinate["bearing_degrees"], } addresses = { "street_number": complete_address.get("street_number"), "street_name": complete_address.get("street_name"), "neighborhood": complete_address.get("neighborhood"), "city": complete_address.get("city"), "state": complete_address.get("state"), "country": complete_address.get("country"), "postal_code": complete_address.get("postal_code"), "latitude": complete_address.get("latitude"), "longitude": complete_address.get("longitude"), } # self.get_destination(coordinate) self.save_to_database(coordinate, addresses) else: message = f"Address couldn't be saved to database. Data returned from reverse_geocode API: {result}" if __name__ != '__main__': print(message) logger.warning(message)