def handle(self, *args, **options): self.google_client = get_geocoder_for_service('google')() while BallotReturned.objects.filter(latitude=None).exists(): try: self.populate_latitude_for_ballots() except GeocoderQuotaExceeded: self.google_client = get_geocoder_for_service('google')() print('Success! All BallotReturned objects now have latitude and longitude populated.')
def handle(self, *args, **options): self.google_client = get_geocoder_for_service('google')() while BallotReturned.objects.filter(latitude=None).exists(): try: self.populate_latitude_for_ballots() except GeocoderQuotaExceeded: self.google_client = get_geocoder_for_service('google')() print( 'Success! All BallotReturned objects now have latitude and longitude populated.' )
def _retrieve_location(query, geocoder, exactly_one, **kwargs): """Retrieves a location from a query. Parameters ---------- query : str Address, query or structured query to geocode. geocoder : str Geocoder to use. Please visit https://geopy.readthedocs.io/ for more info. exactly_one : boolean Whether to retrieve just one location. **kwargs : Keywords arguments for geolocator.geocode(). The user_agent argument is mandatory (this argument can be set as user_agent = 'my-gee-username' or user_agent = 'my-gee-app-name'). Please visit https://geopy.readthedocs.io/ for more info. Returns ------- Location Retrieved location. """ cls = get_geocoder_for_service(geocoder) geolocator = cls(**kwargs) location = geolocator.geocode(query, exactly_one=exactly_one) if location is None: raise Exception("No matches were found for your query!") else: return location
def _query(data, forward, provider, **kwargs): # generic wrapper for calls over lists to geopy Geocoders import geopy from geopy.geocoders.base import GeocoderQueryError from geopy.geocoders import get_geocoder_for_service if not isinstance(data, pd.Series): data = pd.Series(data) if isinstance(provider, string_types): provider = get_geocoder_for_service(provider) coder = provider(**kwargs) results = {} for i, s in iteritems(data): try: if forward: results[i] = coder.geocode(s) else: results[i] = coder.reverse((s.y, s.x), exactly_one=True) except (GeocoderQueryError, ValueError): results[i] = (None, None) time.sleep(_throttle_time(provider)) df = _prepare_geocode_result(results) return df
def _query(data, forward, provider, throttle_time, **kwargs): # generic wrapper for calls over lists to geopy Geocoders from geopy.geocoders.base import GeocoderQueryError from geopy.geocoders import get_geocoder_for_service if forward: if not isinstance(data, pd.Series): data = pd.Series(data) else: if not isinstance(data, geopandas.GeoSeries): data = geopandas.GeoSeries(data) if isinstance(provider, str): provider = get_geocoder_for_service(provider) coder = provider(**kwargs) results = {} for i, s in data.items(): try: if forward: results[i] = coder.geocode(s) else: results[i] = coder.reverse((s.y, s.x), exactly_one=True) except (GeocoderQueryError, ValueError): results[i] = (None, None) time.sleep(throttle_time) df = _prepare_geocode_result(results) return df
def PointFromQuery(query, geocoder="nominatim", **kwargs): '''Constructs an ee.Feature describing a point from a query submitted to a geodocer using the geopy package. This returns exactly one pair of coordinates. The properties of the feature correspond to the raw properties retrieved by the location of the query. Tip ---------- Check more info about constructors in the :ref:`User Guide<Constructors>`. Parameters ---------- query : str Address, query or structured query to geocode. geocoder : str, default = 'nominatim' Geocoder to use. Please visit https://geopy.readthedocs.io/ for more info. **kwargs : Keywords arguments for geolocator.geocode(). The user_agent argument is mandatory (this argument can be set as user_agent = 'my-gee-username' or user_agent = 'my-gee-app-name'). Please visit https://geopy.readthedocs.io/ for more info. Returns ------- ee.Feature Feature with a geometry describing a point from the specified query. See Also -------- BBoxFromQuery : Constructs an ee.Feature describing a bounding box from a query submitted to a geodocer using the geopy package. Examples -------- >>> import ee, eemont >>> ee.Authenticate() >>> ee.Initialize() >>> ee.Feature.PointFromQuery('Mt. Rainier, USA',user_agent = 'my-gee-eemont-query').getInfo() {'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-121.757682, 46.8521484]}, 'properties': {'boundingbox': ['46.8520984', '46.8521984', '-121.757732', '-121.757632'], 'class': 'natural', 'display_name': 'Mount Rainier, Pierce County, Washington, United States', 'importance': 0.5853390667167165, 'lat': '46.8521484', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'lon': '-121.757682', 'osm_id': 1744903493, 'osm_type': 'node', 'place_id': 17287419, 'type': 'volcano'}} ''' cls = get_geocoder_for_service(geocoder) geolocator = cls(**kwargs) location = geolocator.geocode(query) if location == None: raise Exception('No matches were found for your query!') else: geometry = ee.Geometry.Point([location.longitude, location.latitude]) return ee.Feature(geometry, location.raw)
def geocode(self): geocoder_for_service = get_geocoder_for_service(GEOCODING_SERVICE) geocoder = geocoder_for_service(api_key=GOOGLE_MAPS_KEY) geocoded_location = geocoder.geocode(self.name) if geocoded_location: self.latitude = geocoded_location.latitude self.longitude = geocoded_location.longitude else: raise self.CouldNotGeocode("Location: "+self.name)
def PointFromQuery(query, geocoder="nominatim", **kwargs): '''Constructs an ee.Geometry describing a point from a query submitted to a geodocer using the geopy package. This returns exactly one pair of coordinates. Tip ---------- Check more info about constructors in the :ref:`User Guide<Constructors>`. Parameters ---------- query : str Address, query or structured query to geocode. geocoder : str, default = 'nominatim' Geocoder to use. Please visit https://geopy.readthedocs.io/ for more info. **kwargs : Keywords arguments for geolocator.geocode(). The user_agent argument is mandatory (this argument can be set as user_agent = 'my-gee-username' or user_agent = 'my-gee-app-name'). Please visit https://geopy.readthedocs.io/ for more info. Returns ------- ee.Geometry.Point Geometry describing a point from the specified query. See Also -------- BBoxFromQuery : Constructs an ee.Geometry describing a bounding box from a query submitted to a geodocer using the geopy package. MultiPointFromQuery : Constructs an ee.Geometry describing a multi-point from a query submitted to a geodocer using the geopy package. Examples -------- >>> import ee, eemont >>> ee.Authenticate() >>> ee.Initialize() >>> ee.Geometry.PointFromQuery('Mt. Rainier, USA',user_agent = 'my-gee-eemont-query') ee.Geometry({ "functionInvocationValue": { "functionName": "GeometryConstructors.Point", "arguments": { "coordinates": { "constantValue": [ -121.757682, 46.8521484 ] } } } }) ''' cls = get_geocoder_for_service(geocoder) geolocator = cls(**kwargs) location = geolocator.geocode(query) if location is None: raise Exception('No matches were found for your query!') else: return ee.Geometry.Point([location.longitude, location.latitude])
def _get_location_from_geocoder_by_query(query, config): ''' local function for reverse location by query :param query: query: query string for reversing, exapmle: Moscow :param config: dict of params for geocoder :return: location: location object ''' location = None geocoder = get_geocoder_for_service(config.get('service', None)) if geocoder is not None: geolocator = geocoder(**config.get('init', {})) location = geolocator.geocode(query, **config.get('reverse', {})) return location
def _get_location_from_geocoder_by_geoposition(geoposition, config): ''' local function for reverse location by geoposition :param geoposition: geoposition object: string format: "altitude, longitude" :param config: dict of params for geocoder :return: location: location object ''' location = None geocoder = get_geocoder_for_service(config.get('service', None)) if geocoder is not None: geolocator = geocoder(**config.get('init', {})) location = geolocator.reverse(str(geoposition), **config.get('reverse', {})) return location
def geocode(address, api, batch=False, config=None): if api == 'mapquest': params = {'key': mapquest_key, 'location': address, 'maxResults': 1} req = requests.get(url=mapquest_url, params=params) req.raise_for_status() location = json.loads(req.text) #print('Location {}'.format(json.dumps(location, indent=2))) if not batch: geo = (location['results'][0]['locations'][0]['latLng']['lat'], location['results'][0]['locations'][0]['latLng']['lng']) return {'formatted_address': '', 'geo': geo} else: locations = [] for r in location['results']: locations.append({ 'formated_address': r['providedLocation']['location'], 'geo': (r['locations'][0]['latLng']['lat'], r['locations'][0]['latLng']['lng']) }) return locations elif api == 'google': address_detail = gmaps.geocode(address=address) if len(address_detail) == 0: print('No results found? address {}, result {}'.format( address, address_detail)) return None else: formatted_address = address_detail[0]['formatted_address'] geo = address_detail[0]['geometry']['location'] geo = (geo['lat'], geo['lng']) return {'formatted_address': formatted_address, 'geo': geo} else: cls = get_geocoder_for_service(api) geolocator = cls(**config) location = geolocator.geocode(address) return { 'formatted_address': location.address, 'geo': (location.latitude, location.longitude) }
async def address(self, lat=None, lon=None, service="nominatim"): """Find the street adresse the car is on Args: service (str, optional): What type of geodecoder should be used. Returns: str: Street adresse of the car is located on. """ try: from geopy.geocoders import Nominatim, get_geocoder_for_service from geopy.adapters import AioHTTPAdapter except ImportError: _LOGGER.debug("Can't find the current addresse without geopy") return service = get_geocoder_for_service(service) lat = lat or self._data["drive_state"]["latitude"] lon = lon or self._data["drive_state"]["longitude"] async with service( user_agent="teslaapi", adapter_factory=AioHTTPAdapter, ) as geolocator: location = await geolocator.reverse( ( lat, lon, ), exactly_one=True, ) # Ideally this should be in the local format of that country. # https://github.com/mirumee/google-i18n-address if Nominatim is used. # Some providers seem to fix that, arcgis, but i couldnt figure out how # to get the clostst street number if it was at the opposite side of the road. _LOGGER.debug("Lat %s lon %s is %s", lat, lon, location.address) return location.address
def BBoxFromQuery(query,geocoder = "nominatim",**kwargs): '''Constructs an ee.Feature describing a bounding box from a query submitted to a geodocer using the geopy package. The properties of the feature correspond to the raw properties retrieved by the location of the query. Parameters ---------- query : str Address, query or structured query to geocode. geocoder : str, default = 'nominatim' Geocoder to use. One of 'nominatim' or 'arcgis'. Please visit https://geopy.readthedocs.io/ for more info. **kwargs : Keywords arguments for geolocator.geocode(). The user_agent argument is mandatory (this argument can be set as user_agent = 'my-gee-username' or user_agent = 'my-gee-app-name'). Please visit https://geopy.readthedocs.io/ for more info. Returns ------- ee.Feature Feature with a geometry describing a bounding box from the specified query. Examples -------- >>> import ee, eemont >>> ee.Initialize() >>> ee.Feature.BBoxFromQuery('Bogotá',user_agent = 'my-gee-eemont-query').getInfo() {'type': 'Feature', 'geometry': {'geodesic': False, 'type': 'Polygon', 'coordinates': [[[-74.22351370000001, 4.4711754], [-74.0102483, 4.4711754], [-74.0102483, 4.8331695], [-74.22351370000001, 4.8331695], [-74.22351370000001, 4.4711754]]]}, 'properties': {'boundingbox': ['4.4711754', '4.8331695', '-74.2235137', '-74.0102483'], 'class': 'boundary', 'display_name': 'Bogotá, Bogotá Distrito Capital, Región Andina, 11001, Colombia', 'icon': 'https://nominatim.openstreetmap.org/ui/mapicons//poi_boundary_administrative.p.20.png', 'importance': 0.7931743429157826, 'lat': '4.6533326', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'lon': '-74.083652', 'osm_id': 7426387, 'osm_type': 'relation', 'place_id': 259216862, 'type': 'administrative'}} See Also -------- PointFromQuery : Constructs an ee.Feature describing a point from a query submitted to a geodocer using the geopy package. ''' if geocoder in ['nominatim','arcgis']: cls = get_geocoder_for_service(geocoder) else: raise Exception('Invalid geocoder! Use one of "nominatim" or "arcgis".') geolocator = cls(**kwargs) location = geolocator.geocode(query) if location is None: raise Exception('No matches were found for your query!') else: if geocoder == 'nominatim': BBox = location.raw['boundingbox'] geometry = ee.Geometry.BBox(float(BBox[2]),float(BBox[0]),float(BBox[3]),float(BBox[1])) return ee.Feature(geometry,location.raw) elif geocoder == 'arcgis': BBox = location.raw['extent'] geometry = ee.Geometry.BBox(BBox['xmin'],BBox['ymin'],BBox['xmax'],BBox['ymax']) return ee.Feature(geometry,location.raw) else: raise Exception('Invalid geocoder! Use one of "nominatim" or "arcgis".')
def ballot_item_list_edit_process_view(request): """ Process the new or edit ballot form :param request: :return: """ authority_required = {'verified_volunteer'} # admin, verified_volunteer if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) ballot_returned_id = convert_to_int( request.POST.get('ballot_returned_id', 0)) google_civic_election_id = request.POST.get('google_civic_election_id', 0) polling_location_id = convert_to_int( request.POST.get('polling_location_id', 0)) polling_location_city = request.POST.get('polling_location_city', '') polling_location_zip = request.POST.get('polling_location_zip', '') contest_office1_id = request.POST.get('contest_office1_id', 0) contest_office1_order = request.POST.get('contest_office1_order', 0) contest_measure1_id = request.POST.get('contest_measure1_id', 0) election_local_id = 0 # Find existing ballot_returned ballot_returned_found = False ballot_returned = BallotReturned() if positive_value_exists(ballot_returned_id): try: ballot_returned_query = BallotReturned.objects.filter( id=ballot_returned_id) if len(ballot_returned_query): ballot_returned = ballot_returned_query[0] ballot_returned_found = True except Exception as e: pass election_manager = ElectionManager() polling_location_manager = PollingLocationManager() polling_location = PollingLocation() polling_location_found = False try: if ballot_returned_found: # Update # Check to see if this is a We Vote-created election is_we_vote_google_civic_election_id = True \ if convert_to_int(ballot_returned.google_civic_election_id) >= 1000000 \ else False results = election_manager.retrieve_election( ballot_returned.google_civic_election_id) if results['election_found']: election = results['election'] election_local_id = election.id # polling_location must be found # We cannot change a polling location once saved, so we ignore the incoming polling_location_id here results = polling_location_manager.retrieve_polling_location_by_id( 0, ballot_returned.polling_location_we_vote_id) if results['polling_location_found']: polling_location = results['polling_location'] polling_location_found = True else: # Create new ballot_returned entry # election must be found election_results = election_manager.retrieve_election( google_civic_election_id) if election_results['election_found']: election = election_results['election'] election_local_id = election.id state_code = election.get_election_state() else: messages.add_message( request, messages.ERROR, 'Could not find election -- ' 'required to save ballot_returned.') return HttpResponseRedirect( reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id, )) + "?google_civic_election_id=" + str(google_civic_election_id) + "&polling_location_id=" + str(polling_location_id) + "&polling_location_city=" + polling_location_city + "&polling_location_zip=" + str(polling_location_zip)) # polling_location must be found if positive_value_exists(polling_location_id): results = polling_location_manager.retrieve_polling_location_by_id( polling_location_id) if results['polling_location_found']: polling_location = results['polling_location'] polling_location_found = True if not polling_location_found: messages.add_message( request, messages.ERROR, 'Could not find polling_location -- ' 'required to save ballot_returned.') return HttpResponseRedirect( reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id, )) + "?google_civic_election_id=" + str(google_civic_election_id) + "&polling_location_id=" + str(polling_location_id) + "&polling_location_city=" + polling_location_city + "&polling_location_zip=" + str(polling_location_zip)) ballot_returned = BallotReturned( election_date=election.election_day_text, election_description_text=election.election_name, google_civic_election_id=google_civic_election_id, polling_location_we_vote_id=polling_location.we_vote_id, normalized_city=polling_location.city, normalized_line1=polling_location.line1, normalized_line2=polling_location.line2, normalized_state=polling_location.state, normalized_zip=polling_location.get_formatted_zip(), text_for_map_search=polling_location.get_text_for_map_search(), ) ballot_returned.save() ballot_returned_id = ballot_returned.id ballot_returned_found = True messages.add_message(request, messages.INFO, 'New ballot_returned saved.') # ####################################### # Make sure we have saved a latitude and longitude for the ballot_returned entry if ballot_returned_found and positive_value_exists( ballot_returned.text_for_map_search): if not ballot_returned.latitude or not ballot_returned.longitude: google_client = get_geocoder_for_service('google')() location = google_client.geocode( ballot_returned.text_for_map_search) if location is None: status = 'Could not find location matching "{}"'.format( ballot_returned.text_for_map_search) else: ballot_returned.latitude = location.latitude ballot_returned.longitude = location.longitude ballot_returned.save() # ####################################### # Now create new ballot_item entries # Contest Office 1 ballot_item_manager = BallotItemManager() contest_office_manager = ContestOfficeManager() results = contest_office_manager.retrieve_contest_office( contest_office1_id) if results['contest_office_found']: contest_office = results['contest_office'] ballot_item_display_name = contest_office.office_name google_ballot_placement = 0 measure_subtitle = '' local_ballot_order = contest_office1_order if positive_value_exists( contest_office1_order) else 0 results = ballot_item_manager.update_or_create_ballot_item_for_polling_location( polling_location.we_vote_id, google_civic_election_id, google_ballot_placement, ballot_item_display_name, measure_subtitle, local_ballot_order, contest_office.id, contest_office.we_vote_id) if results['new_ballot_item_created']: messages.add_message(request, messages.INFO, 'Office 1 added.') else: messages.add_message(request, messages.ERROR, 'Office 1 could not be added.') # Contest Measure 1 ballot_item_manager = BallotItemManager() contest_measure_manager = ContestMeasureManager() results = contest_measure_manager.retrieve_contest_measure( contest_measure1_id) if results['contest_measure_found']: contest_measure = results['contest_measure'] google_ballot_placement = 0 ballot_item_display_name = contest_measure.measure_title contest_office_id = 0 contest_office_we_vote_id = '' local_ballot_order = 0 ballot_item_manager.update_or_create_ballot_item_for_polling_location( polling_location.we_vote_id, google_civic_election_id, google_ballot_placement, ballot_item_display_name, contest_measure.measure_subtitle, local_ballot_order, contest_office_id, contest_office_we_vote_id, contest_measure.id) except Exception as e: messages.add_message(request, messages.ERROR, 'Could not save ballot_returned.') return HttpResponseRedirect( reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id, )) + "?google_civic_election_id=" + str(google_civic_election_id) + "&polling_location_id=" + str(polling_location_id) + "&polling_location_city=" + polling_location_city + "&polling_location_zip=" + str(polling_location_zip))
def test_fail(self): """ get_geocoder_for_service unknown service """ with self.assertRaises(GeocoderNotFound): get_geocoder_for_service("")
def BBoxFromQuery(query, geocoder="nominatim", **kwargs): '''Constructs an ee.Geometry describing a bounding box from a query submitted to a geodocer using the geopy package. Parameters ---------- query : str Address, query or structured query to geocode. geocoder : str, default = 'nominatim' Geocoder to use. One of 'nominatim' or 'arcgis'. Please visit https://geopy.readthedocs.io/ for more info. **kwargs : Keywords arguments for geolocator.geocode(). The user_agent argument is mandatory (this argument can be set as user_agent = 'my-gee-username' or user_agent = 'my-gee-app-name'). Please visit https://geopy.readthedocs.io/ for more info. Returns ------- ee.Geometry.Polygon Geometry describing a bounding box from the specified query. Examples -------- >>> import ee, eemont >>> ee.Initialize() >>> ee.Geometry.BBoxFromQuery('Seattle',user_agent = 'my-gee-eemont-query') ee.Geometry({ "functionInvocationValue": { "functionName": "GeometryConstructors.Polygon", "arguments": { "coordinates": { "constantValue": [ [ [ -122.45969600000001, 47.7341357 ], [ -122.45969600000001, 47.4810022 ], [ -122.224433, 47.4810022 ], [ -122.224433, 47.7341357 ] ] ] }, "geodesic": { "constantValue": false } } } }) See Also -------- PointFromQuery : Constructs an ee.Geometry describing a point from a query submitted to a geodocer using the geopy package. MultiPointFromQuery : Constructs an ee.Geometry describing a multi-point from a query submitted to a geodocer using the geopy package. ''' if geocoder in ['nominatim', 'arcgis']: cls = get_geocoder_for_service(geocoder) else: raise Exception( 'Invalid geocoder! Use one of "nominatim" or "arcgis".') geolocator = cls(**kwargs) location = geolocator.geocode(query) if location is None: raise Exception('No matches were found for your query!') else: if geocoder == 'nominatim': BBox = location.raw['boundingbox'] return ee.Geometry.BBox(float(BBox[2]), float(BBox[0]), float(BBox[3]), float(BBox[1])) elif geocoder == 'arcgis': BBox = location.raw['extent'] return ee.Geometry.BBox(BBox['xmin'], BBox['ymin'], BBox['xmax'], BBox['ymax']) else: raise Exception( 'Invalid geocoder! Use one of "nominatim" or "arcgis".')
from django.conf import settings from django.core.cache import cache from geopy.geocoders import get_geocoder_for_service from common.helpers import normalize_name # use google by default _geocoder_service = get_geocoder_for_service(getattr(settings, 'GEO_SERVICE', 'google')) # a dictionary of key, value for kwargs _geocoder_settings = { 'api_key': getattr(settings, 'GEO_API_KEY', None), 'client_id': getattr(settings, 'GEO_CLIENT_ID', None), 'secret_key': getattr(settings, 'GEO_SECRET_KEY', None) } geocoder = _geocoder_service(**_geocoder_settings) def address_to_location(address): """convert a raw address to location""" key = normalize_name(address) address = address.encode('utf-8') location = cache.get(key) if location is None: location = geocoder.geocode(address) cache.set(key, location) return location
def test_get_geocoder_for_service(self): self.assertEqual(get_geocoder_for_service("google"), GoogleV3) self.assertEqual(get_geocoder_for_service("googlev3"), GoogleV3)
def test_get_geocoder_for_service(self): assert get_geocoder_for_service("google") == GoogleV3 assert get_geocoder_for_service("googlev3") == GoogleV3
def service(self): if not self.service_cache: service = geocoders.get_geocoder_for_service(self.service_default) self.service_cache = service(user_agent=MightyConfig.domain) return self.service_cache
def MultiPointFromQuery(query, geocoder="nominatim", **kwargs): '''Constructs an ee.Feature describing a point from a query submitted to a geodocer using the geopy package. This returns all pairs of coordinates retrieved by the query. The properties of the feature collection correspond to the raw properties retrieved by the locations of the query. Tip ---------- Check more info about constructors in the :ref:`User Guide<Constructors>`. Parameters ---------- query : str Address, query or structured query to geocode. geocoder : str, default = 'nominatim' Geocoder to use. Please visit https://geopy.readthedocs.io/ for more info. **kwargs : Keywords arguments for geolocator.geocode(). The user_agent argument is mandatory (this argument can be set as user_agent = 'my-gee-username' or user_agent = 'my-gee-app-name'). Please visit https://geopy.readthedocs.io/ for more info. Returns ------- ee.FeatureCollection Feature Collection with point geometries from the specified query. Examples -------- >>> import ee, eemont >>> ee.Authenticate() >>> ee.Initialize() >>> ee.FeatureCollection.MultiPointFromQuery('Río Amazonas',user_agent = 'my-gee-eemont-query').getInfo() {'type': 'FeatureCollection', 'columns': {'boundingbox': 'List<String>', 'class': 'String', 'display_name': 'String', 'importance': 'Float', 'lat': 'String', 'licence': 'String', 'lon': 'String', 'osm_id': 'Integer', 'osm_type': 'String', 'place_id': 'Integer', 'system:index': 'String', 'type': 'String'}, 'features': [{'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-57.4801276, -2.3740229]}, 'id': '0', 'properties': {'boundingbox': ['-4.4421898', '0.7065296', '-73.4501259', '-49.2759133'], 'class': 'waterway', 'display_name': 'Rio Amazonas, Região Norte, 69100-143, Brasil', 'importance': 0.4, 'lat': '-2.3740229', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'lon': '-57.4801276', 'osm_id': 2295651, 'osm_type': 'relation', 'place_id': 258650987, 'type': 'river'}}, {'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-70.04978704421745, -4.10958645]}, 'id': '1', 'properties': {'boundingbox': ['-4.2647706', '-3.9548576', '-70.1817875', '-69.9440055'], 'class': 'natural', 'display_name': 'Río Amazonas, Ramón Castilla, Mariscal Ramón Castilla, Loreto, Perú', 'importance': 0.39999999999999997, 'lat': '-4.10958645', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'lon': '-70.04978704421745', 'osm_id': 8495385, 'osm_type': 'relation', 'place_id': 297654614, 'type': 'water'}}, ...]} ''' cls = get_geocoder_for_service(geocoder) geolocator = cls(**kwargs) locations = geolocator.geocode(query, exactly_one=False) if locations is None: raise Exception('No matches were found for your query!') else: features = [] for location in locations: geometry = ee.Geometry.Point( [location.longitude, location.latitude]) feature = ee.Feature(geometry, location.raw) features.append(feature) return ee.FeatureCollection(features)
def geocode(geocoder, config, query, query_config): cls = geocoders.get_geocoder_for_service(geocoder) geolocator = cls(**config) location = geolocator.geocode(query, **query_config) return location
def test_get_geocoder_for_service_raises_for_unknown(self): with self.assertRaises(GeocoderNotFound): get_geocoder_for_service("")
def ballot_item_list_edit_process_view(request): """ Process the new or edit ballot form :param request: :return: """ authority_required = {'verified_volunteer'} # admin, verified_volunteer if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) ballot_returned_id = convert_to_int(request.POST.get('ballot_returned_id', 0)) google_civic_election_id = request.POST.get('google_civic_election_id', 0) polling_location_id = convert_to_int(request.POST.get('polling_location_id', 0)) polling_location_city = request.POST.get('polling_location_city', '') polling_location_zip = request.POST.get('polling_location_zip', '') contest_office1_id = request.POST.get('contest_office1_id', 0) contest_office1_order = request.POST.get('contest_office1_order', 0) contest_measure1_id = request.POST.get('contest_measure1_id', 0) election_local_id = 0 # Find existing ballot_returned ballot_returned_found = False ballot_returned = BallotReturned() if positive_value_exists(ballot_returned_id): try: ballot_returned_query = BallotReturned.objects.filter(id=ballot_returned_id) if len(ballot_returned_query): ballot_returned = ballot_returned_query[0] ballot_returned_found = True except Exception as e: pass election_manager = ElectionManager() polling_location_manager = PollingLocationManager() polling_location = PollingLocation() polling_location_found = False try: if ballot_returned_found: # Update # Check to see if this is a We Vote-created election is_we_vote_google_civic_election_id = True \ if convert_to_int(ballot_returned.google_civic_election_id) >= 1000000 \ else False results = election_manager.retrieve_election(ballot_returned.google_civic_election_id) if results['election_found']: election = results['election'] election_local_id = election.id # polling_location must be found # We cannot change a polling location once saved, so we ignore the incoming polling_location_id here results = polling_location_manager.retrieve_polling_location_by_id( 0, ballot_returned.polling_location_we_vote_id) if results['polling_location_found']: polling_location = results['polling_location'] polling_location_found = True else: # Create new ballot_returned entry # election must be found election_results = election_manager.retrieve_election(google_civic_election_id) if election_results['election_found']: election = election_results['election'] election_local_id = election.id state_code = election.get_election_state() else: messages.add_message(request, messages.ERROR, 'Could not find election -- ' 'required to save ballot_returned.') return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) + "?google_civic_election_id=" + str(google_civic_election_id) + "&polling_location_id=" + str(polling_location_id) + "&polling_location_city=" + polling_location_city + "&polling_location_zip=" + str(polling_location_zip) ) # polling_location must be found if positive_value_exists(polling_location_id): results = polling_location_manager.retrieve_polling_location_by_id(polling_location_id) if results['polling_location_found']: polling_location = results['polling_location'] polling_location_found = True if not polling_location_found: messages.add_message(request, messages.ERROR, 'Could not find polling_location -- ' 'required to save ballot_returned.') return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) + "?google_civic_election_id=" + str(google_civic_election_id) + "&polling_location_id=" + str(polling_location_id) + "&polling_location_city=" + polling_location_city + "&polling_location_zip=" + str(polling_location_zip) ) ballot_returned = BallotReturned( election_date=election.election_day_text, election_description_text=election.election_name, google_civic_election_id=google_civic_election_id, polling_location_we_vote_id=polling_location.we_vote_id, normalized_city=polling_location.city, normalized_line1=polling_location.line1, normalized_line2=polling_location.line2, normalized_state=polling_location.state, normalized_zip=polling_location.get_formatted_zip(), text_for_map_search=polling_location.get_text_for_map_search(), ) ballot_returned.save() ballot_returned_id = ballot_returned.id ballot_returned_found = True messages.add_message(request, messages.INFO, 'New ballot_returned saved.') # ####################################### # Make sure we have saved a latitude and longitude for the ballot_returned entry if ballot_returned_found and positive_value_exists(ballot_returned.text_for_map_search): if not ballot_returned.latitude or not ballot_returned.longitude: google_client = get_geocoder_for_service('google')() location = google_client.geocode(ballot_returned.text_for_map_search) if location is None: status = 'Could not find location matching "{}"'.format(ballot_returned.text_for_map_search) else: ballot_returned.latitude = location.latitude ballot_returned.longitude = location.longitude ballot_returned.save() # ####################################### # Now create new ballot_item entries # Contest Office 1 ballot_item_manager = BallotItemManager() contest_office_manager = ContestOfficeManager() results = contest_office_manager.retrieve_contest_office(contest_office1_id) if results['contest_office_found']: contest_office = results['contest_office'] ballot_item_display_name = contest_office.office_name google_ballot_placement = 0 measure_subtitle = '' local_ballot_order = contest_office1_order if positive_value_exists(contest_office1_order) else 0 results = ballot_item_manager.update_or_create_ballot_item_for_polling_location( polling_location.we_vote_id, google_civic_election_id, google_ballot_placement, ballot_item_display_name, measure_subtitle, local_ballot_order, contest_office.id, contest_office.we_vote_id) if results['new_ballot_item_created']: messages.add_message(request, messages.INFO, 'Office 1 added.') else: messages.add_message(request, messages.ERROR, 'Office 1 could not be added.') # Contest Measure 1 ballot_item_manager = BallotItemManager() contest_measure_manager = ContestMeasureManager() results = contest_measure_manager.retrieve_contest_measure(contest_measure1_id) if results['contest_measure_found']: contest_measure = results['contest_measure'] google_ballot_placement = 0 ballot_item_display_name = contest_measure.measure_title contest_office_id = 0 contest_office_we_vote_id = '' local_ballot_order = 0 ballot_item_manager.update_or_create_ballot_item_for_polling_location( polling_location.we_vote_id, google_civic_election_id, google_ballot_placement, ballot_item_display_name, contest_measure.measure_subtitle, local_ballot_order, contest_office_id, contest_office_we_vote_id, contest_measure.id) except Exception as e: messages.add_message(request, messages.ERROR, 'Could not save ballot_returned.') return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) + "?google_civic_election_id=" + str(google_civic_election_id) + "&polling_location_id=" + str(polling_location_id) + "&polling_location_city=" + polling_location_city + "&polling_location_zip=" + str(polling_location_zip) )
###### Version 1 ##### ###### Importing File and making dataset##### import pandas as pd df_icmrlab = pd.read_csv("/kaggle/input/covid19-in-india/ICMRTestingLabs.csv") from geopy.geocoders import get_geocoder_for_service get_geocoder_for_service("nominatim") import geopy.geocoders from geopy.geocoders import Nominatim geopy.geocoders.options.default_user_agent = 'my_app/1' geopy.geocoders.options.default_timeout = 7 geolocator = Nominatim() from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="my_app/1") from geopy.extra.rate_limiter import RateLimiter geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) temp = df_icmrlab['city'].apply(geocode) point = temp.apply(lambda loc: tuple(loc.point) if loc else None) df_icmrlab['location'] = point df_icmrlab.to_csv('ICMRLabDetails.csv', index=False) ##### Version 2 ##### ##### Inserting Location Column and inserting data in location column ##### temp = df_icmrlab['pincode'].apply(geocode) point = temp.apply(lambda loc: tuple(loc.point) if loc else None) df_icmrlab['location'] = point df_icmrlab.to_csv('ICMRLabDetails.csv', index=False) df_icmrlab.head(10) df_icmrlab[df_icmrlab.isna().any(axis=1)] ##### Version 3 #####
def test_ok(self): """ get_geocoder_for_service """ self.assertEqual(get_geocoder_for_service("google"), GoogleV3) self.assertEqual(get_geocoder_for_service("googlev3"), GoogleV3)
def pick_geocoder(service): print(get_geocoder_for_service(service))
def MultiPointFromQuery(query, geocoder="nominatim", **kwargs): '''Constructs an ee.Geometry describing a multi-point from a query submitted to a geodocer using the geopy package. This returns all pairs of coordinates retrieved by the query. Parameters ---------- query : str Address, query or structured query to geocode. geocoder : str, default = 'nominatim' Geocoder to use. Please visit https://geopy.readthedocs.io/ for more info. **kwargs : Keywords arguments for geolocator.geocode(). The user_agent argument is mandatory (this argument can be set as user_agent = 'my-gee-username' or user_agent = 'my-gee-app-name'). Please visit https://geopy.readthedocs.io/ for more info. Returns ------- ee.Geometry.MultiPoint Geometry describing a multi-point from the specified query. Examples -------- >>> import ee, eemont >>> ee.Initialize() >>> ee.Geometry.MultiPointFromQuery('Mt. Rainier, USA',user_agent = 'my-gee-eemont-query') ee.Geometry({ "functionInvocationValue": { "functionName": "GeometryConstructors.MultiPoint", "arguments": { "coordinates": { "constantValue": [ [ -121.757682, 46.8521484 ], [ -76.9649751, 38.9415 ], [ -97.78689, 30.154197 ], [ -84.130098, 39.863452 ] ] } } } }) See Also -------- BBoxFromQuery : Constructs an ee.Geometry describing a bounding box from a query submitted to a geodocer using the geopy package. PointFromQuery : Constructs an ee.Geometry describing a point from a query submitted to a geodocer using the geopy package. ''' cls = get_geocoder_for_service(geocoder) geolocator = cls(**kwargs) locations = geolocator.geocode(query, exactly_one=False) if locations is None: raise Exception('No matches were found for your query!') else: coords = [] for location in locations: coords.append([location.longitude, location.latitude]) return ee.Geometry.MultiPoint(coords)