def cli(location, **kwargs): "Geocode an arbitrary number of strings from Command Line." locations = [] # Read Standard Input # $ cat foo.txt | geocode try: for line in fileinput.input(): locations.append(line.strip()) except: pass # Read multiple files & user input location for item in location: if os.path.exists(item): with open(item, 'rb') as f: locations += f.read().splitlines() else: locations.append(item) # Distance calcuation if kwargs['distance']: d = geocoder.distance(locations, **kwargs) click.echo(d) return # Geocode results from user input for location in locations: g = geocoder.get(location.strip(), **kwargs) try: click.echo(json.dumps(g.__getattribute__(kwargs['output']))) except IOError: # When invalid command is entered a broken pipe error occurs return
def _check_input(self, location): # Checking for a LatLng String if isinstance(location, string_types): expression = r"[-]?\d+[.]?[-]?[\d]+" pattern = re.compile(expression) match = pattern.findall(location) if len(match) == 2: lat, lng = match self._check_for_list([lat, lng]) else: # Check for string to Geocode using a provider provider = self.kwargs.get('provider', 'osm') g = geocoder.get(location, provider=provider) if g.ok: self.lat, self.lng = g.lat, g.lng # Checking for List of Tuple elif isinstance(location, (list, tuple)): self._check_for_list(location) # Checking for Dictionary elif isinstance(location, dict): self._check_for_dict(location) # Checking for a Geocoder Class elif hasattr(location, 'latlng'): if location.latlng: self.lat, self.lng = location.latlng # Result into Error else: raise ValueError("Unknown location: %s" % location)
def locate_point(self, track=0, segment=0, point=0): # noqa """Determine name of place for point. Saves that in point.name for caching. Args: track, segment, point: Indices into the list track or point may also be a real GPXTrackPoint. Returns: tuple(name, located) name is the name of the location located is True if locating was needed, False if we had it cached """ # pylint: disable=too-many-branches if isinstance(track, GPXTrackPoint): point = track if not isinstance(point, GPXTrackPoint): point = self.tracks[track].segments[segment].points[point] result = not point.name if result: # point.name = 'dummy' # for faster testing # return point.name, True parts = [] _ = Geocoder_location([point.latitude, point.longitude]) place = geocoder.get(location=_, provider='osm', method='reverse') if place.raw is None: point.name = 'Water' return point.name, True fields = dict() for _ in ('city', 'town', 'village', 'hamlet'): if hasattr(place, _): value = getattr(place, _) if value: fields[_] = value if 'address' in place.raw: fields.update(place.raw['address']) name = None prefer = ['town', 'suburb', 'village', 'hamlet', 'town', 'city', 'school'] for _ in prefer: if _ in fields: name = fields[_] break if not name: name = place.address if name: parts.append(name) if not self.default_country or place.country.lower() != self.default_country.lower(): parts.append(place.country or place.country_code) try: point.name = ','.join(parts) except TypeError: logging.error( 'Parsing geo info: %r country=%r(default %r) -> %r', place.raw, place.country, self.default_country, parts) raise return point.name, result
def get_cached(location, **kwargs): """ Simple wrapper that adds Django caching support to 'geocoder.get()'. """ result = cache.get(location) # Result is not cached or wrong if not result or not result.ok: result = geocoder.get(location, **kwargs) if result.ok: cache.set(location, result) return result
async def reverse_geocode(self, service): latitude = None longitude = None location = None entity = None if ATTR_PERSON in service.data: person = self._hass.states.get( _get_entity_id(PERSON_DOMAIN, service.data[ATTR_PERSON])) entity_id = person.attributes.get(ATTR_SOURCE, None) else: entity_id = service.data(ATTR_ENTITY_ID, None) if entity_id: entity = self._hass.states.get(entity_id) latitude = entity.attributes.get(ATTR_LATITUDE, None) longitude = entity.attributes.get(ATTR_LONGITUDE, None) elif ATTR_LOCATION in service.data: latitude = service.data[ATTR_LATITUDE] longitude = service.data[ATTR_LONGITUDE] if latitude and longitude: location = [latitude, longitude] if not location: _LOGGER.error( "Unable to determine location from service data: %s" % str(service.data)) return try: result = geocoder.get(location, provider=self.provider, method="reverse") if result.ok: if entity: entity.attributes = \ (entity.attributes or {})[ATTR_GEOCODED_ADDRESS] = result.address _LOGGER.info('Geocoded address for %f, %f: %s' % (latitude, longitude, result.address)) return result.address else: _LOGGER.error('Error retrieving address from provider %s' % self.provider) except Exception as e: _LOGGER.error('Error connecting to provider %s: %s' % (self.provider, str(e))) return None
def _check_input(self, location): # Checking for a LatLng String if isinstance(location, (str, unicode)): expression = r"[-]?\d+[.]?[-]?[\d]+" pattern = re.compile(expression) match = pattern.findall(location) if len(match) == 2: lat, lng = match self._check_for_list([lat, lng]) else: # Check for string to Geocode using a provider provider = self.kwargs.get('provider', 'osm') g = geocoder.get(location, provider=provider) if g.ok: self.lat, self.lng = g.lat, g.lng # Checking for List of Tuple elif isinstance(location, (list, tuple)): self._check_for_list(location) # Checking for Dictionary elif isinstance(location, dict): self._check_for_dict(location) # Checking for a Geocoder Class elif hasattr(location, 'latlng'): if location.latlng: self.lat, self.lng = location.latlng # Result into Error else: print('[ERROR] Please provide a correct location\n' '>>> g = geocoder.location("Ottawa ON")\n' '>>> g = geocoder.location([45.23, -75.12])\n' '>>> g = geocoder.location("45.23, -75.12")\n' '>>> g = geocoder.location({"lat": 45.23, "lng": -75.12})') sys.exit()
def __init__(self, places, gpxfiles): """See class docstring.""" self.places = places self.gpxfiles = gpxfiles self.locations = list() for place in places: _ = geocoder.get(place, provider='osm') if not _: raise Exception('Place not found: {}'.format(place)) self.locations.append(_[0]) logging.info('using locations:') for _ in self.locations: logging.info(' %s', _.address) self.distances = list() gpx_points = [ GPXTrackPoint(latitude=x.lat, longitude=x.lng) for x in self.locations ] for gpxfile in gpxfiles: self.distances.append((gpxfile, [ gpxfile.gpx.get_nearest_location(x).location.distance_2d(x) for x in gpx_points ])) self.distances.sort(key=lambda x: sum(x[1]))
print 'Permits:', len(container) print 'Geocoded:', len(container_geocoder) ip = geocoder.maxmind().ip # Loop inside all permits for item in container: location = item if location: # Only find ones that don't exist in Geocoder DB if not location in container_geocoder: if provider == 'ottawa': previous_location = location location = location.replace(', Ottawa, ON', '') # Geocode address g = geocoder.get(location, provider=provider, timeout=15.0) result = g.geojson if provider == 'ottawa': result['properties']['location'] = previous_location # Break if OVER QUERY using Google if g.status in ['OVER_QUERY_LIMIT']: print 'Over QUERY' os.system('nmcli con down id CyberGhost') time.sleep(60*5) print 'Shuting Down CyberGhost...' os.system('nmcli con up id CyberGhost') time.sleep(10) print 'Cyberghost Active!' ip = geocoder.maxmind().ip
container_geocoder[item['properties'].get('location')] = True # Print Results print 'Provider:', provider print 'Permits:', len(container) print 'Geocoded:', len(container_geocoder) # Loop inside all permits for item in container: location = item.get('location') if location: # Only find ones that don't exist in Geocoder DB if not location in container_geocoder: # Geocode address g = geocoder.get(location, provider=provider, timeout=15.0) # Break if OVER QUERY using Google if g.status in ['OVER_QUERY_LIMIT']: print 'Over QUERY' exit() os.system('nmcli con down id CyberGhost') time.sleep(60 * 5) print 'Shuting Down CyberGhost...' os.system('nmcli con up id CyberGhost') time.sleep(10) print 'Cyberghost Active!' elif g.status in ['ZERO_RESULTS']: db_geocoder.insert(g.geojson) print provider, 'Added ZERO:', location elif g.ok:
def geocoder_get(self, location, provider, timeout): return geocoder.get(location, provider=provider, session=self.requests_session, timeout=timeout)