Exemplo n.º 1
0
def getcity(s):
    gc = geocoding.geocode(gmaps, s)
    try:
        country = [
            g["long_name"] for g in gc[0]["address_components"]
            if "country" in g["types"]
        ][0]
    except IndexError:
        return ["Unable to precisely locate."]
    try:
        state = [
            g["long_name"] for g in gc[0]["address_components"]
            if "administrative_area_level_1" in g["types"]
        ][0]
    except IndexError:
        try:
            city = [
                g["long_name"] for g in gc[0]["address_components"]
                if "locality" in g["types"]
            ][0]
            return city, country
        except IndexError:
            return [country]
    try:
        city = [
            g["long_name"] for g in gc[0]["address_components"]
            if "locality" in g["types"]
        ][0]
        return city, state, country
    except IndexError:
        return state, country
Exemplo n.º 2
0
    def Geocode(self, Address):

        results = ggeo.geocode(self.GoogleClient, address=Address, region="GR")


        # If Weird Results Let Me Know and return
        try:
            if results[0]["geometry"]["location"]:
                locationData = results[0]["geometry"]["location"]
        except IndexError:
            try:
                print "First Error"
                print results[0]["geometry"]
            except IndexError:
                try:
                    print "Second Error"
                    print results[0]
                except IndexError:
                    print "Third Error"
                    print Address
                    print results
                    return [None, None, None]

        address = results[0]["formatted_address"]
        return (address, locationData["lng"], locationData["lat"])
Exemplo n.º 3
0
def get_coordinates(address):
    """
    Get coordinates.
    :param address: Returned address from 'input.get_address()'
    :return: A set of coordinates
    """
    geocode_result = geocoding.geocode(gm_client, address)
    if geocode_result:
        coordinates = {
            "address": address,
            "street": "",
            "city": "",
            "formatted_address": geocode_result[0]['formatted_address'],
            "lat": geocode_result[0]['geometry']['location']['lat'],
            "lng": geocode_result[0]['geometry']['location']['lng'],
            "place_id": geocode_result[0]['place_id'],
            "status": "OK"
        }
        # If the first component of an address is a locality (city).
        if geocode_result[0]['address_components'][0]['types'] == [
                'locality', 'political'
        ]:
            coordinates['city'] = geocode_result[0]['address_components'][0][
                'long_name']
        # Else look for a street.
        else:
            for item in geocode_result[0]['address_components']:
                if item['types'] == ['route']:
                    coordinates['street'] = item['long_name']
        return coordinates
    else:
        coordinates = {"status": "FAIL"}
        return coordinates
Exemplo n.º 4
0
def get_location(gmaps, locations):
    identified_locations = []
    lat = ''
    long = ''
    for location in locations:
        if location in identified_locations or not location.isalpha():
            continue
        address = geocoding.geocode(gmaps, location)
        admins = []
        if len(address) == 0: continue
        for i in range(len(address[0]['address_components'])):
            loc = address[0]['address_components'][i]['long_name']
            postal_code_type = address[0]['address_components'][i]['types'][0]
            if postal_code_type == 'postal_code':
                continue
            # if loc not in identified_locations:
            admins.append(loc)
        # print(admins)
        if 'India' not in admins:
            continue
        if len(identified_locations) < len(admins):
            lat = address[0]['geometry']['location']['lat']
            long = address[0]['geometry']['location']['lng']
            identified_locations = admins
        #identified_locations.extend(admins)
    identified_locations.reverse()
    if not identified_locations:
        identified_locations.append(locations[0] if locations else "")

    return identified_locations, lat, long
Exemplo n.º 5
0
def _collect_geocoded_address(text, default=None):
    """Collect user address data interactively.

    This function geocodes user input using Google Maps and prompts the user to
    confirm the geocoded address before returning. The user is prompted to
    try again when there are zero or multiple geocoding candidates.

    Arguments:
        text: The text to show for the prompt

    Returns:
         str: The formatted_address from a Google Maps geocode operation
    """
    while True:
        user_address = click.prompt(text, default=default, prompt_suffix=CLI_PROMPT_SUFFIX, type=click.STRING)

        geocoded = geocoding.geocode(MAPS_CLIENT, user_address)
        if len(geocoded) == 0:
            print("Google Maps can't find that address. Please be more " "specific.")
        elif len(geocoded) > 1:
            # TODO List up to three of the results
            print("Google Maps found multiple results with that address. " "Please be more specific.")
        elif "partial_match" in geocoded[0]:
            print(
                "Google Maps found a partial match: " + geocoded[0]["formatted_address"] + ". Please be more "
                "specific."
            )
        else:
            formatted_address = geocoded[0]["formatted_address"]
            if click.confirm(
                "Is the correct address " + formatted_address + "?", prompt_suffix=CLI_PROMPT_SUFFIX, default=True
            ):
                return formatted_address
Exemplo n.º 6
0
def get_geoloc(client, addr):
    for old, new in [(u'פינת', '&'), (u'אזו"ת', ''), (u'אזוה"ת', ''),
                     (u"אזוה''ת", '')]:
        addr = addr.replace(old, new)
    loc = geocode(client, addr, language='iw')
    if len(loc) == 0:
        return None
    geoloc = loc[0]['geometry']['location']
    return Point(latitude=geoloc['lat'], longitude=geoloc['lng'])
Exemplo n.º 7
0
def get_nearby():
    args = request.args
    # if len(args) not in range(1,4):
    #    return {"error": "not enough arguments"}
    address = args.get('address')
    rad = args.get('radius')
    print("args:", args)
    geo = geocoding.geocode(gmaps, address)
    lat = geo[0]['geometry']['location']['lat']
    lng = geo[0]['geometry']['location']['lng']
    nearby = places.places_nearby(gmaps,
                                  location=(lat, lng),
                                  radius=1,
                                  type="restaurant")
    return nearby
Exemplo n.º 8
0
    def getlocation(self, address):
    #----------------------------------------------------------------------
        '''
        retrieve location from database, if available, else get from googlemaps api

        :param address: address for lookup
        :rtype: Location instance
        '''

        dbaddress = address
        if len(dbaddress) > MAX_LOCATION_LEN:
            dbaddress = dbaddress[0:MAX_LOCATION_LEN]

        loc = Location.query.filter_by(name=dbaddress).first()

        now = epoch2dt(time.time())
        if not loc or (now - loc.cached_at > CACHE_REFRESH):
            # new location
            loc = Location(name=dbaddress)

            # get geocode from google
            # use the full address, not dbaddress which gets s
            gc = geocode(self.client, address=address)

            # if we got good data, fill in the particulars
            # assume first in list is good, give warning if multiple entries received back
            if gc:
                # notify if multiple values returned
                if len(gc) > 1:
                    app.logger.warning('geocode: multiple locations ({}) received from googlemaps for {}'.format(len(gc), address))

                # save lat/long from first value returned
                loc.latitude  = gc[0]['geometry']['location']['lat']
                loc.longitude = gc[0]['geometry']['location']['lng']

            # if no response, still store in database, but flag as error
            else:
                loc.lookuperror = True

            # remember when last retrieved
            loc.cached_at = now

            # insert or update -- flush is done within, so id should be set after this
            insert_or_update(db.session, Location, loc, skipcolumns=['id'], name=dbaddress)

        # and back to caller
        return loc
Exemplo n.º 9
0
def _collect_geocoded_address(text, default=None):
    """Collect user address data interactively.

    This function geocodes user input using Google Maps and prompts the user to
    confirm the geocoded address before returning. The user is prompted to
    try again when there are zero or multiple geocoding candidates.

    Arguments:
        text: The text to show for the prompt

    Returns:
         str: The formatted_address from a Google Maps geocode operation
    """
    while True:
        user_address = click.prompt(text,
                                    default=default,
                                    prompt_suffix=CLI_PROMPT_SUFFIX,
                                    type=click.STRING)

        geocoded = geocoding.geocode(MAPS_CLIENT, user_address)
        if len(geocoded) == 0:
            print("Google Maps can't find that address. Please be more "
                  "specific.")
        elif len(geocoded) > 1:
            # TODO List up to three of the results
            print("Google Maps found multiple results with that address. "
                  "Please be more specific.")
        elif "partial_match" in geocoded[0]:
            print("Google Maps found a partial match: " +
                  geocoded[0]["formatted_address"] + ". Please be more "
                  "specific.")
        else:
            formatted_address = geocoded[0]["formatted_address"]
            if click.confirm("Is the correct address " + formatted_address +
                             "?",
                             prompt_suffix=CLI_PROMPT_SUFFIX,
                             default=True):
                return formatted_address
Exemplo n.º 10
0
def getlatlong(s):
    return geocoding.geocode(gmaps, s)[0]["geometry"]["location"]
Exemplo n.º 11
0
 def coords(self, address):
     return [(y['lat'], y['lng']) for y in
             [x['geometry']['location'] for x in geocoding.geocode(self.client, address=address, language="el")]]
Exemplo n.º 12
0
 def coords(self, address):
     return [(y['lat'], y['lng']) for y in [
         x['geometry']['location'] for x in geocoding.geocode(
             self.client, address=address, language="el")
     ]]
Exemplo n.º 13
0
import googlemaps
from dotenv import load_dotenv
from googlemaps.geocoding import geocode

load_dotenv()

gmaps = googlemaps.Client(key=os.environ.get('GOOGLE_API_KEY'))

with open('public/json/mouvements.json', 'r') as mouvements_json:
    mouvements = json.load(mouvements_json)

    for mouvement in mouvements:
        if 'geocode' not in mouvement:
            mouvement['geocode'] = geocode(gmaps,
                                           mouvement['ADRESSE'] + ' ' +
                                           mouvement['COMMUNE'],
                                           region='fr')
        geocode_result = mouvement['geocode']
        print(geocode_result)
        if 'geo' not in mouvement:
            if len(geocode_result) >= 1:
                mouvement['geo'] = geocode_result[0]['geometry']['location']
        else:
            if mouvement['geo']['lat'] is None or mouvement['geo'][
                    'lng'] is None:
                pass

with open('public/json/mouvements.json', 'w') as mouvements_json:
    json.dump(mouvements, mouvements_json, indent=4)
Exemplo n.º 14
0
def get_geocode(client, city: str) -> tuple:
    data = geocoding.geocode(client, city)
    return data[0]['geometry']['location']['lng'], data[0]['geometry'][
        'location']['lat']