Python googlemaps.Client() Examples

The following are code examples for showing how to use googlemaps.Client(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: SearchAroundBot   Author: kercos   File: geoUtils.py    GNU General Public License v3.0 6 votes vote down vote up
def getLocationTest1():
    newport_ri = (41.49008, -71.312796)
    cleveland_oh = (41.499498, -81.695391)
    return vincenty(newport_ri, cleveland_oh).kilometers


# ================================
# ================================
# ================================


#gmaps = googlemaps.Client(key=key.GOOGLE_API_KEY)

# def test_Google_Map_Api():
#     # Geocoding an address
#     geocode_result = gmaps.geocode('bari')
#     logging.debug("gmaps geocode result: " + str(geocode_result))
#     return geocode_result

    # Look up an address with reverse geocoding
    #reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452)) 
Example 2
Project: Lunchotron   Author: James-Firth   File: runbot.py    MIT License 6 votes vote down vote up
def main():
	global lunchotron_config
	logging.basicConfig()
	curr_dir = os.path.dirname(os.path.realpath(__file__))
	sys.path.append(curr_dir)

	lunchotron_config = ConfigParser.ConfigParser()
	lunchotron_config.read("config.ini")

	settings.API_TOKEN = lunchotron_config.get("slack", "API_TOKEN")
	settings.gPlaces = GooglePlaces(lunchotron_config.get("google-places", "API_TOKEN"))
	settings.gmaps = googlemaps.Client(lunchotron_config.get("google-places", "API_TOKEN"))
	settings.location = lunchotron_config.get("google-places", "location")

	settings.PLUGINS = ["lunchotron"] #Overwrites other plugins. Don't need upload for instance.
	bot = Bot()
	print "[[ lunchotron online ]]"
	bot.run() 
Example 3
Project: batch-geocoder   Author: clintonreece   File: batch_geocoder.py    The Unlicense 6 votes vote down vote up
def check_auth():
    """Check for a Google Maps Geocoding API key.

    For authentication to work you must have a Google Maps Geocoding API key
    and the GOOGLE_API_KEY environment variable must be exported:

    >>> export GOOGLE_API_KEY=AI...

    :return: Google Maps Geocoding API key
    :rtype: string
    """
    api_key = os.environ["GOOGLE_API_KEY"]
    try:
        gmaps = googlemaps.Client(key=api_key)
        gmaps.geocode('San Francisco, CA')
    except ValueError:
        if not api_key:
            logging.error('GOOGLE_API_KEY not set.')
        else:
            logging.error('GOOGLE_API_KEY rejected by the server.')
    return api_key 
Example 4
Project: Google-street-view-street-side-image-parser   Author: zxh009123   File: GoogleStreetViewParser.py    MIT License 6 votes vote down vote up
def __init__(self, setting_file):
        settings_file = open(setting_file)
        settings = json.load(settings_file)

        try:
            self.GOOGLE_KEY = settings["GOOGLE_KEY"]
            self.DISTANCES = settings["DISTANCES"]
            self.FILE = settings["FILE"]
            self.ROOT_FOLDER = settings["ROOT_FOLDER"]
        except:
            print("please config settings correctly")
            exit(-1)

        self.gmaps = googlemaps.Client(key = self.GOOGLE_KEY)

        self.stops = self.read_csv(self.FILE)

        self.stop_name_to_index = [] 
Example 5
Project: OpenPoGoBot   Author: tehp   File: __init__.py    MIT License 6 votes vote down vote up
def boot(service_container):
    # PoGoApi parameters
    config = service_container.get('config.core')

    if os.path.isfile(os.path.join(os.getcwd(), config['load_library'])):
        config['load_library'] = os.path.join(os.getcwd(), config['load_library'])

    service_container.set_parameter('pogoapi.provider', config['login']['auth_service'])
    service_container.set_parameter('pogoapi.username', config['login']['username'])
    service_container.set_parameter('pogoapi.password', config['login']['password'])
    service_container.set_parameter('pogoapi.shared_lib', config['load_library'])

    service_container.register_singleton('pgoapi', PGoApi())
    service_container.register_singleton('google_maps', googlemaps.Client(key=config["mapping"]["gmapkey"]))

    if config['movement']['path_finder'] in ['google', 'direct']:
        service_container.set_parameter('path_finder', config['movement']['path_finder'] + '_path_finder')
    else:
        raise Exception('You must provide a valid path finder')

    if config['movement']['navigator'] in ['fort', 'waypoint', 'camper']:
        service_container.set_parameter('navigator', config['movement']['navigator'] + '_navigator')
    else:
        raise Exception('You must provide a valid navigator') 
Example 6
Project: OpenPoGoBot   Author: tehp   File: mapper_test.py    MIT License 6 votes vote down vote up
def test_find_location_with_coordinates_invalid_response():
        config = create_core_test_config()
        api_wrapper = create_mock_api_wrapper(config)
        google_maps = Mock(spec=Client)
        google_maps.elevation = Mock(return_value=None)
        location = Mock()
        location.latitude = 51.5044524
        location.longitude = -0.0752479
        location.altitude = 10.1
        google_maps.geocode = Mock(return_value=location)
        logger = Mock()
        logger.log = Mock(return_value=None)
        mapper = Mapper(config, api_wrapper, google_maps, logger)

        lat, lng, alt = mapper.find_location('51.5044524, -0.0752479')

        assert lat == 51.5044524
        assert lng == -0.0752479
        assert alt == 10.1 
Example 7
Project: osedev   Author: osedev   File: models.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def clean(self):

        if self.is_current and not self.is_osedev:
            raise ValidationError({
                'is_current': _("To enable current status a user must also be an OSE Developer.")
            })

        if not self.location:
            self.latitude = None
            self.longitude = None
            self.location_details = None
        elif settings.GEOCODE_ENABLED and settings.GOOGLE_API_KEY:
            if not self.__original_location or (self.__original_location != self.location):
                gmaps = googlemaps.Client(key=settings.GOOGLE_API_KEY)
                self.location_details = gmaps.geocode(self.location)
                if self.location_details:
                    self.latitude = self.location_details[0]['geometry']['location']['lng']
                    self.longitude = self.location_details[0]['geometry']['location']['lat'] 
Example 8
Project: fabulous   Author: Eulercoder   File: directions.py    GNU General Public License v3.0 6 votes vote down vote up
def directions(start, end, unsafe=False):

    mapService = GoogleMaps(GOOGLE_DIRECTION_API)

    payload = {'origin':start, 'destination':end}
    result = requests.get(DIRECTIONS_BASEURL, params=payload)
    result = result.json()
    responce = ''

    try:
        if result['status'] == "OK":
            for i in range (0, len (result['routes'][0]['legs'][0]['steps'])):
                j = result['routes'][0]['legs'][0]['steps'][i]['html_instructions']
                responce +=strip_tags(j)+'\n'

            return responce
        else:
            ''' Will be replaced with logging in future'''
            print(result['status'])
            print(result['error_message'])
            return ERROR_MSG
    except KeyError as e:
        ''' Need to be logged'''
        return ERROR_MSG 
Example 9
Project: greentastic   Author: jannisborn   File: api_requests.py    MIT License 6 votes vote down vote up
def get_autocomplete(query, location, radius=50000):
    """
    Receives a query for GoogleMaps and returns a sorted list of best destinations.
    Args:
        - QUERY {string}.  The possibly incomplete target location.
        - LOCATION {string, dict, list, or tuple}. The user location, ideally a list
            of two GPS coordinates. 
        - RADIUS {int}. The radius in meter used to restrict the search proposals.
            Defaults to 50km.
    
    Returns:
        - SUGGESTIONS {list}. A sorted list of best destinations.
    """

    places = GMAPS.places_autocomplete(query, radius=radius, location=location)
    suggestions = [place.get('description', ) for place in places]
    return suggestions 
Example 10
Project: property-finder   Author: googlemaps   File: models.py    Apache License 2.0 5 votes vote down vote up
def set_google_maps_fields(self, latlng=None):
        """
        Uses the Google Maps API to set:
          - geocoded latlng
          - nearest school name + distance
          - nearest train station name + distance
        """
        client = Client(key=settings.GOOGLE_MAPS_API_SERVER_KEY)
        if not latlng:
            data = client.geocode(self.address)
            if not data:
                raise Exception("Unable to resolve the address: '%s'" % address)
            latlng = data[0]["geometry"]["location"]
        self.point = GEOSGeometry("POINT(%(lng)s %(lat)s)" % latlng)

        error = ""
        for field in ("school", "train_station"):
            try:
                place = client.places_nearby(location=latlng, rank_by="distance", type=field)["results"][0]
            except IndexError:
                continue
            except Exception as e:
                error = e
                continue
            setattr(self, "nearest_%s" % field, place["name"])
            place_latlng = place["geometry"]["location"]
            d = distance((latlng["lat"], latlng["lng"]), (place_latlng["lat"], place_latlng["lng"])).km
            setattr(self, "nearest_%s_distance" % field, round(d, 2))
        if error:
            raise Exception(error) 
Example 11
Project: UberLens   Author: adamalawrence   File: GMapsWrapper.py    MIT License 5 votes vote down vote up
def __init__(self):
        APIKEY = self.readAPI_key()
        self.gmaps = googlemaps.Client(key=APIKEY) 
Example 12
Project: UberLens   Author: adamalawrence   File: GMapsWrapper.py    MIT License 5 votes vote down vote up
def __init__(self, KEY):
        # APIKEY = self.readAPI_key()
        self.gmaps = googlemaps.Client(key=KEY) 
Example 13
Project: tcc   Author: alexandrevicenzi   File: geo.py    MIT License 5 votes vote down vote up
def get_geo_code(latitude, longitude):
    try:
        gmaps = googlemaps.Client(key=API_KEY)
        result = gmaps.reverse_geocode((latitude, longitude))
        return GeoCode(result)
    except:
        traceback.print_exc()

    return None 
Example 14
Project: tcc   Author: alexandrevicenzi   File: geo.py    MIT License 5 votes vote down vote up
def get_directions(origin_latitude, origin_longitude, destination_latitude, destination_longitude):
    '''
        Get the distance between to points.
    '''
    try:
        gmaps = googlemaps.Client(key=API_KEY)
        result = gmaps.directions((origin_latitude, origin_longitude), (destination_latitude, destination_longitude),
                                  mode='driving', units='metric', language='pt-BR')
                                  #mode='transit', units='metric', language='pt-BR', transit_mode='bus')
        if len(result) == 1:
            return Direction(result)
    except:
        traceback.print_exc()

    return None 
Example 15
Project: tcc   Author: alexandrevicenzi   File: geo.py    MIT License 5 votes vote down vote up
def get_distances_wrap(origins, destinations):
    '''
        Get the distances between many points.
        Returns an interpolated dict, where's the key is
        origin and destination (interpolated) and the value is
        the distance between these points.
    '''
    try:
        origins = list(origins)
        destinations = list(destinations)

        gmaps = googlemaps.Client(key=API_KEY)
        result = gmaps.distance_matrix(origins, destinations,
                                       mode='driving', units='metric')
                                       #mode='transit', units='metric', transit_mode='bus')
        if result['status'] == 'OK':
            matrix = {}

            for i, origin in enumerate(origins):
                for j, destination in enumerate(destinations):
                    data = result['rows'][i]['elements'][j]
                    if data['status'] == 'OK':
                        matrix[(origin, destination)] = Distance(data)

            if matrix:
                return matrix
    except:
        traceback.print_exc()

    return None 
Example 16
Project: user_similarity   Author: sunshengjing   File: SimilarityMetric.py    The Unlicense 5 votes vote down vote up
def check_googleMap(self, location):
         gmaps = Client(key='AIzaSyDAALCs0fN4bo9GdYeplrjdkpg6Lc8LpiU')
         #lat,lan = gmaps.address_to_latlng(location)
         ginfo = gmaps.geocode(location)
         dic = ginfo[0]
         lat = dic.get('geometry').get('bounds').get('northeast').get('lat')
         lng = dic.get('geometry').get('bounds').get('northeast').get('lng')
         return [lat,lng] 
Example 17
Project: commute.py   Author: dhruvbaldawa   File: __init__.py    MIT License 5 votes vote down vote up
def get_all_paths(config_file, src, dst, when=None):
    """
    Utility function to compute the paths between a source and destination
    given a config file and time.

    config_file: path to the config file
    src: source
    dst: destination
    when: start of commute unix timestamp
    """
    with open(config_file) as f:
        global config
        config = yaml.load(f.read())

    if src not in config['places'] or dst not in config['places']:
        raise Exception("source or destination are not valid")

    if when is None:
        when = int(time.time())

    client = googlemaps.Client(key=config['api_key'])
    g = build_graph(config['map'])
    return sorted(((path_rank(path), path)
                   for path in find_all_paths(g, client,
                                              src, dst,
                                              when)),
                  key=lambda x: x[0]) 
Example 18
Project: gopro-streetview   Author: llarco   File: streetview_uploader.py    MIT License 5 votes vote down vote up
def _init_google_maps_api(args):
    """Initializes the Google Maps API client."""
    global _GOOGLE_MAPS_API
    _GOOGLE_MAPS_API = googlemaps.Client(key=args.googlemaps_key) 
Example 19
Project: homefinder   Author: jaona   File: homefinder.py    MIT License 5 votes vote down vote up
def __init__(self):
        """Constructor."""
        self.placemarks = []
        self.distance_matrix = []
        self.key = os.environ.get('HOMEFINDER_GOOGLE_API_TOKEN')
        self.gmaps = googlemaps.Client(self.key) 
Example 20
Project: TIANE   Author: FerdiKr   File: navigation.py    GNU General Public License v3.0 5 votes vote down vote up
def handle(text, tiane, local_storage):
    text = text.lower()
    length = len(text)

    gmaps = googlemaps.Client(key='')

    # get locations
    matchLocations = re.search('von', text)
    if matchLocations != None:
        startLocations = matchLocations.end() + 1
        locations = text[startLocations:length]

        matchMiddle = re.search('(bis|nach)', text)
        if matchMiddle != None:
            startMiddle = matchMiddle.start() - 1
            endMiddle = matchMiddle.end() + 1

    origin = text[startLocations:startMiddle]
    destination = text[endMiddle:length]

    # get distance and duration
    directions_result = gmaps.distance_matrix(origin,destination,language='de')

    durationTxt = directions_result['rows'][0]['elements'][0]['duration']['text']
    distanceTxt = directions_result['rows'][0]['elements'][0]['distance']['text']

    match = re.search('km', distanceTxt)
    if match != None:
        endNumber = match.start() - 1
        distanceTxt = distanceTxt[0:endNumber]

        distance = float(re.sub(",", ".", distanceTxt))

    tiane.say('Von '+origin+' nach '+destination+' sind es '+distanceTxt+' Kilometer. Die Fahrt dauert '+durationTxt) 
Example 21
Project: batch-geocoder   Author: clintonreece   File: batch_geocoder.py    The Unlicense 5 votes vote down vote up
def geocode_addresses(address_df, address_limit, api_key):
    """Geocode addresses in a DataFrame.

    :param address_df: DataFrame with columns either:
                       | Index | Address |
                       or optionally:
                       | Index | Address | Latitude | Longitude |
    :type address_df: DataFrame

    :param api_key: Google Maps Geocoding API key
    :type api_key: string

    :return: DataFrame updated with geocoded addresses
    :rtype: DataFrame
    """
    # Start API client
    gmaps = googlemaps.Client(key=api_key)

    # Create address list, truncate if limit argument specified
    address_list = address_df['Address'].tolist()
    print address_df
    if address_limit:
        address_list = address_list[:address_limit]

    # <-- Geocoding loop -->
    for address_id, address in enumerate(tqdm(address_list)):
        geocode_result = []
        # Address NaN -> don't geocode and set to default
        if pd.isnull(address_list[address_id]):
            latitude, longitude = 0, 0
        else:
            geocode_result = gmaps.geocode(address)
        # Geocode_results empty -> latitude, longitude == 0,0
        if geocode_result:
            latitude = geocode_result[0]['geometry']['location']['lat']
            longitude = geocode_result[0]['geometry']['location']['lng']
        address_df.at[address_id, 'Latitude'] = latitude
        address_df.at[address_id, 'Longitude'] = longitude

    return address_df 
Example 22
Project: myplace   Author: vinihcampos   File: main.py    MIT License 5 votes vote down vote up
def create_client(project_id):
    return datastore.Client(project_id) 
Example 23
Project: jupyter-mortgage   Author: mrled   File: streetmap.py    The Unlicense 5 votes vote down vote up
def geocode(self, address, zoomlevel=14):
        client = googlemaps.Client(key=self.apikey)
        geocodes = client.geocode(address)
        georesults = []

        for idx, geocode in enumerate(geocodes):
            geocode = namedtupled.map(geocodes[idx])

            coordinates = (
                geocode.geometry.location.lat,
                geocode.geometry.location.lng)
            displayname = geocode.formatted_address

            county = "Unknown"
            neighborhood = "Unknown"
            for component in geocode.address_components:
                if "administrative_area_level_2" in component.types:
                    county = component.long_name
                elif "neighborhood" in component.types:
                    neighborhood = component.long_name

            figure = self.map(geocode.coordinates, zoomlevel)
            georesults.append(GeocodeResult(
                coordinates, displayname, neighborhood, county, figure))

        return georesults 
Example 24
Project: mycommunity   Author: cacarrara   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def _set_lat_lng(self):
        gmaps = googlemaps.Client(key=settings.GOOGLE_API_KEY)
        geocode = gmaps.geocode(self.address)
        if len(geocode) > 0:
            self.latitude = geocode[0]['geometry']['location']['lat']
            self.longitude = geocode[0]['geometry']['location']['lng'] 
Example 25
Project: eclipse2017   Author: google   File: geo.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super(Geo, self).__init__(**kwargs)

        self.name = 'geo'
        self.import_name = __name__

        self._routes = (
            ('/', 'root', self.root, ('GET',)),
            ('/timezone', 'timezone', self.timezone, ('GET',)))

        self.gmaps = googlemaps.Client(key=GOOGLE_MAPS_API_KEY,
                                       timeout=TIMEOUT,
                                       retry_timeout=RETRY_TIMEOUT) 
Example 26
Project: eclipse2017   Author: google   File: determine_state.py    Apache License 2.0 5 votes vote down vote up
def main():
    args = get_arguments()

    TIMEOUT=30
    RETRY_TIMEOUT=30
    gmaps = googlemaps.Client(key=args.google_maps_api_key,
                              timeout=TIMEOUT,
                              retry_timeout=RETRY_TIMEOUT)
    # Load photo points
    r = pickle.load(open(args.filtered_photo_metadata))
    f = partial(get_state, gmaps)
    p = Pool(5)
    results = p.map(f, r)
    pickle.dump(dict(results), open(args.state_output, "wb")) 
Example 27
Project: eclipse2017   Author: google   File: gps.py    Apache License 2.0 5 votes vote down vote up
def apply_timezone_offset(lat, lon, camera_datetime):
    TIMEOUT=3
    RETRY_TIMEOUT=5
    gmaps = googlemaps.Client(key=GOOGLE_MAPS_API_KEY,
                              timeout=TIMEOUT,
                              retry_timeout=RETRY_TIMEOUT)
    tz = gmaps.timezone((lat, lon))
    offset = tz.get('rawOffset', 0)
    dstOffset = tz.get('dstOffset', 0)
    td = datetime.timedelta(seconds=offset + dstOffset)
    return camera_datetime - td 
Example 28
Project: OpenPoGoBot   Author: tehp   File: mapper_test.py    MIT License 5 votes vote down vote up
def test_init():
        config = create_core_test_config()
        api_wrapper = create_mock_api_wrapper(config)
        google_maps = Mock(spec=Client)
        logger = Mock()
        logger.log = Mock(return_value=None)
        mapper = Mapper(config, api_wrapper, google_maps, logger)

        assert mapper.config == config
        assert mapper.api_wrapper == api_wrapper
        assert mapper.google_maps == google_maps 
Example 29
Project: OpenPoGoBot   Author: tehp   File: mapper_test.py    MIT License 5 votes vote down vote up
def test_get_cells_no_response():
        account = test_account_name()
        config = create_core_test_config({
            "login": {
                "username": account
            },
            "mapping": {
                "cell_radius": 500
            }
        })
        api_wrapper = create_mock_api_wrapper(config)
        google_maps = Mock(spec=Client)
        logger = Mock()
        logger.log = Mock(return_value=None)
        mapper = Mapper(config, api_wrapper, google_maps, logger)

        api_wrapper.set_position(51.5044524, -0.0752479, 10)

        pgo = api_wrapper.get_api()
        pgo.set_response("get_map_objects", {})
        api_wrapper.call = Mock(return_value=None)

        # Clean up any old location logs
        if os.path.isfile('data/last-location-'+account+'.json'):
            os.unlink('data/last-location-'+account+'.json')

        cells = mapper.get_cells(51.5044524, -0.0752479)

        assert len(cells) == 0 
Example 30
Project: OpenPoGoBot   Author: tehp   File: mapper_test.py    MIT License 5 votes vote down vote up
def test_find_location_with_coordinates():
        config = create_core_test_config()
        api_wrapper = create_mock_api_wrapper(config)
        google_maps = Mock(spec=Client)
        google_maps.elevation = Mock(return_value=[{'elevation': 10.1}])
        logger = Mock()
        logger.log = Mock(return_value=None)
        mapper = Mapper(config, api_wrapper, google_maps, logger)

        lat, lng, alt = mapper.find_location('51.5044524, -0.0752479')

        assert lat == 51.5044524
        assert lng == -0.0752479
        assert alt == 10.1 
Example 31
Project: where-to-live   Author: cxong   File: finder.py    MIT License 5 votes vote down vote up
def find_locales_inside(gmaps: googlemaps.Client, au_suburbs: pd.DataFrame, address: str):
    target = munchify(gmaps.geocode(address)[0])
    bounds = target.geometry.bounds
    return au_suburbs.loc[
        (au_suburbs.lat >= bounds.southwest.lat) &
        (au_suburbs.lat <= bounds.northeast.lat) &
        (au_suburbs.lon >= bounds.southwest.lng) &
        (au_suburbs.lon <= bounds.northeast.lng)
    ]


# approximate radius of earth in km 
Example 32
Project: where-to-live   Author: cxong   File: finder.py    MIT License 5 votes vote down vote up
def __init__(self, gm_key: str):
        self._gmaps = googlemaps.Client(key=gm_key)
        self.suburbs = self._load_au_suburbs() 
Example 33
Project: spanky.py   Author: gc-plp   File: weather.py    GNU General Public License v3.0 5 votes vote down vote up
def create_maps_api(bot):
    global ds_key

    google_key = bot.config.get("api_keys", {}).get("google_dev_key", None)

    if google_key:
        data.maps_api = googlemaps.Client(google_key)
    else:
        data.maps_api = None

    ds_key = bot.config.get("api_keys", {}).get("darksky", None) 
Example 34
Project: LocusQuarter   Author: arnabsinha4u   File: locus_quarter.py    MIT License 5 votes vote down vote up
def __init__(self, config):
        """
        Generic function to parse the provided confiuration file
        and populate the global variables
        """

        try:
            self.config = config
            parser = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
            parser.read(config)

            #List of variables for Locus Quarter customization
            self.g_list_of_regions_urls = ast.literal_eval(parser.get('LOCUS-QUARTER', 'g_list_of_regions_urls'))
            self.g_list_nearby_types_of_places = ast.literal_eval(parser.get('LOCUS-QUARTER', 'g_list_nearby_types_of_places'))
            self.g_travel_mode = ast.literal_eval(parser.get('LOCUS-QUARTER', 'g_travel_mode'))
            self.g_limit_houses = parser.getint('LOCUS-QUARTER', 'g_limit_houses')
            self.g_limit_search_places_nearby = parser.getint('LOCUS-QUARTER', 'g_limit_search_places_nearby')
            self.g_office_addresses = ast.literal_eval(parser.get('LOCUS-QUARTER', 'g_office_addresses'))
            self.g_office_travel_mode = ast.literal_eval(parser.get('LOCUS-QUARTER', 'g_office_travel_mode'))

            #List of variables for configuring Google Developer Account for API access
            self.g_google_maps_client_api_key = parser.get('GOOGLE-API', 'g_google_maps_client_api_key')
            self.g_google_maps_client_api_client = googlemaps.Client(key=self.g_google_maps_client_api_key)
        except configparser.DuplicateOptionError as ErrDupConfigVal:
            lq_logger.critical('Duplicate value found %s' %ErrDupConfigVal)
            raise
        except AttributeError as AttrError:
            lq_logger.critical('Missing key:value in config file %s' %AttrError)
            raise
        except Exception as err:
            lq_logger.critical("Execution error: %s" %err)
            raise 
Example 35
Project: brumadinho_location   Author: sosbrumadinho   File: views.py    MIT License 5 votes vote down vote up
def get_elevation(lat, lng):
    gmaps = googlemaps.Client(key=settings.GMAPS_API_KEY)
    geocode_result = gmaps.elevation((lat, lng))
    return geocode_result[0]['elevation'] 
Example 36
Project: Geolocalizer   Author: kartta-labs   File: geolocalizer.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, api_key):
    if not api_key:
      raise ValueError('A Google Maps Geocoding API key is required.')
    self.gmaps = googlemaps.Client(key=api_key)
    self.vision_client = vision.ImageAnnotatorClient()
    self.nlp_client = language.LanguageServiceClient() 
Example 37
Project: Zillowbnb   Author: mag3141592   File: zillowbnb.py    MIT License 5 votes vote down vote up
def get_city_location(address, api_key=GOOGLE_API_KEY):
    """
    Uses Google's API to convert location to latitude and longitude.
    Used in centering the map.

    :params address string:
    :returns location list:
    """

    gmaps = Client(api_key)
    geocode = gmaps.geocode(address)
    location = list(geocode[0]['geometry']['location'].values())
    return location 
Example 38
Project: text-yelp   Author: YangVincent   File: yelp_and_chill.py    MIT License 5 votes vote down vote up
def google_directions(ori, dest, mo):
    
    message = []

    gmaps = googlemaps.Client(key = gmaps_key)
    
    now = datetime.now()
    directions_result = None
    try: 
        directions_result = gmaps.directions(origin=ori, destination=dest, mode=mo, departure_time = now, avoid='tolls')
    
    except:
        return("A network error occurred; please try again")
    
    if directions_result == None:
        return("An error occurred; please check your inputs and try again")
    
    message.append("Start from: " + directions_result[0]['legs'][0]['start_address'])
    message.append("End at: " + directions_result[0]['legs'][0]['end_address'])
    message.append("Duration: " + directions_result[0]['legs'][0]['duration']['text'])
    message.append("Distance: " + directions_result[0]['legs'][0]['distance']['text'])
    
    regex = re.compile('<[^>]*>')
    style_regex = re.compile('<[^>]*(style)[^>]*>')
    for each in directions_result[0]['legs'][0]['steps']:
        instr = re.sub(style_regex, '; ', each['html_instructions'])
        instr = re.sub(regex, '', instr)
        message.append(instr)

    return '\n'.join(message) 
Example 39
Project: property-finder   Author: googlemaps   File: populate_random.py    Apache License 2.0 4 votes vote down vote up
def handle(self, **options):
    
        client = googlemaps.Client(key=settings.GOOGLE_MAPS_API_SERVER_KEY)
        properties = []
        start_lat, start_lng = map(float, options["center"].split(","))
        step = {"lat": 3.0, "lng": 5.0}
        seen = set()
        
        for i in range(options["num"] + 1, 1, -1):
            # Random latlng within a boundary that grows out from the center 
            # as iteration occurs.
            latlng = {
                "lat": random.uniform(start_lat + (step["lat"]/i), start_lat - (step["lat"]/i)),
                "lng": random.uniform(start_lng - (step["lng"]/i), start_lng + (step["lng"]/i)),
            }
            try:
                result = client.reverse_geocode(latlng)[0]
                address = result["formatted_address"]
                latlng = result["geometry"]["location"]
            except Exception as e:
                print "Error: %s" % e
                continue
            # Resolved addresses aren't always postal addresses - they could represent a landmark
            # or area of some sort. Sticking with addresses that being with a digit works 
            # reasonably well.
            if not address[0].isdigit():
                print "Skipping non-postal address: %s" % address
                continue
            # Discard duplicates
            if address in seen:
                print "Skipping duplicate address: %s" % address
                continue
            seen.add(address)
            property = Property(address=address)
            property.set_google_maps_fields(latlng=latlng)
            # Set a random value for each of the range fields.
            for field in ("bedrooms", "bathrooms", "car_spaces", "property_type"):
                setattr(property, field, random.choice(Property._meta.get_field(field).choices)[0])
            property.description = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut 
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco 
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in 
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat 
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
            properties.append(property)
            print "Resolved %s" % address
        
        if options["delete"]:
            print "Deleting %s old properties" % Property.objects.count()
            Property.objects.all().delete()
        Property.objects.bulk_create(properties)
        print "Inserted %s properties" % len(properties) 
Example 40
Project: n.ai   Author: mingtaiha   File: google_maps.py    MIT License 4 votes vote down vote up
def get_distance_matrix(start, stores, depart_delay):

    # :param start: Address as a string.
    #   E.g. '1600 Pennsylvania Ave NW, Washington, DC 20006'

    # :param stores: List of Addresses, each element as a string

    # :depart_delay: A nonnegative amount of time (in seconds)
    #       and used to query traffic conditions of when user
    #       leaves relative to when the function is called

    # Generates a distance and time matrix between start locations and stores
    # Matrix is represented as a matrix of (duration_in_traffic, distance)
    # The rows represent starting locations, the columns represent ending
    # locations. The indexing format always follows [start, *stores]

    # Create Google Maps client with Server Key
    #gmaps = googlemaps.Client(key=app.config["GOOGLE_MAPS_API_KEY"])
    GOOGLE_MAPS_API_KEY = "AIzaSyC7gFkRVm3oUKLC3ZTNmuSAxSnXxXhGh0M"
    gmaps = googlemaps.Client(GOOGLE_MAPS_API_KEY)

    # Create list of lat/lng for start location and stores
    start_list = list()
    gcode_start = gmaps.geocode(start)
    #pprint(gcode_start)
    loc_list = list()
    loc_list.append(gcode_start[0]['geometry']['location'])

    for store in stores:
        gcode_store = gmaps.geocode(store)
        #pprint(gcode_store)
        loc_list.append(gcode_store[0]['geometry']['location'])

    #pprint(start_list)

    # Setting Departure Time
    depart_time = int(time.time()) + depart_delay

    # Get Google Maps client to make distance matrix
    d_mat = gmaps.distance_matrix(loc_list, loc_list, departure_time=depart_time, mode='driving', units='miles')

    #pprint(d_mat)

    # Cleaning distance matrix to be a list of list of (duration_in_traffic, distance)
    # The row index corresponds to the start address, col index corresponds to end address
    # Matrix is symmetric
    distance_matrix = list()
    for src in range(len(d_mat['rows'])):
        tmp_list = list()
        for dst in range(len(d_mat['rows'][src]['elements'])):
            tmp_list.append((d_mat['rows'][src]['elements'][dst]['duration_in_traffic']['value'] / 60., \
                            d_mat['rows'][src]['elements'][dst]['distance']['value'] / 1000.))
        distance_matrix.append(tmp_list)

    pprint(distance_matrix)
    return distance_matrix 
Example 41
Project: OpenPoGoBot   Author: tehp   File: mapper_test.py    MIT License 4 votes vote down vote up
def test_get_cells(self):
        account = test_account_name()
        config = create_core_test_config({
            "debug": True,
            "login": {
                "username": account,
            },
            "mapping": {
                "cell_radius": 500
            }
        })
        api_wrapper = create_mock_api_wrapper(config)
        google_maps = Mock(spec=Client)
        logger = Mock()
        logger.log = Mock(return_value=None)
        mapper = Mapper(config, api_wrapper, google_maps, logger)

        api_wrapper.set_position(51.5044524, -0.0752479, 10)

        pgo = api_wrapper.get_api()
        pgo.set_response("get_map_objects", {
            "map_cells": [
                self._create_map_cell(1),
                self._create_map_cell(2),
                self._create_map_cell(3),
                self._create_map_cell(4),
                self._create_map_cell(5)
            ]
        })

        # Clean up any old location logs
        if os.path.isfile('data/last-location-'+account+'.json'):
            os.unlink('data/last-location-'+account+'.json')

        cells = mapper.get_cells(51.5044524, -0.0752479)

        assert len(cells) == 5

        assert bool(os.path.isfile('data/last-location-'+account+'.json')) is True
        with open('data/last-location-'+account+'.json') as data_file:
            data = json.load(data_file)
            assert data["lat"] == 51.5044524
            assert data["lng"] == -0.0752479

        os.unlink('data/last-location-'+account+'.json') 
Example 42
Project: ZomatoCrawl   Author: ethan-hunt-007   File: Road_Map5.py    GNU General Public License v2.0 4 votes vote down vote up
def main():
    global my_loc,gmaps,R
    R=6373
    from_res = input("Enter the starting restaurant:-")
    to_res = input("Enter upto how many restaurant u wan't to see:-")
    path = "C:\Users\Jayant\Desktop\Tomato\Tomato_db_sorted.csv"
    #My Location : 22.587212, 88.374389
    gmaps = googlemaps.Client(key='AIzaSyAMdDIbyp5N8MqwvVvmqwsD4-vgUoLqSRg')
    my_loc = (22.587212, 88.374389)
    res_loc,xy = get_loc(path)
    G=nx.Graph()
    G.add_node("My_Location%s"%str(my_loc),pos=my_loc)
    c=1
    res=1
    node_hash = {}
    for loc in xy[from_res:to_res]:
        print res
        try:
            location = get_directions(loc)
        except:
            print loc
        nodes = [["My_Location%s"%str(my_loc),my_loc]]
        for locs in location[1:-1]:
            node = str(locs)
            '''node = get_address(locs)
            if c not in nodes:
                G.add_node(c,pos=locs)
            nodes.append(c)
            c=c+1'''
            if not G.has_node(node):
                G.add_node(node,pos=locs)
            nodes.append([node,locs])
        G.add_node("Res#%d%s"%(res,node),pos=loc)
        nodes.append(["Res#%d%s"%(res,node),loc])
        res+=1
        for i in xrange(1,len(nodes)):
            G.add_edge(nodes[i-1][0],nodes[i][0],weight=findDistance(nodes[i-1][1][0],nodes[i][1][0],nodes[i-1][1][1],nodes[i][1][1]))
    pos = nx.get_node_attributes(G,'pos')
    nx.draw(G,pos)
    plt.show()
    #print_edge(G)
    save_edgelist(G) 
Example 43
Project: ZomatoCrawl   Author: ethan-hunt-007   File: RoadMap_weight_Is_Edge_Count.py    GNU General Public License v2.0 4 votes vote down vote up
def main():
    global my_loc,gmaps,R,keys,zones
    #zones={"shyambazar metro station":(22.601343,88.372822),"dum dum metro station":(22.621250,88.392888),"salt lake nicco park":(22.571143,88.421805)}
    zones=[(22.534667,88.337770),(22.583298,88.351593),(22.596139,88.451369),(22.499317,88.370983),(22.629245,88.385053),(22.651829,88.427262),(22.593104,88.470083),(22.587207, 88.374325)]
    keys=['AIzaSyAMdDIbyp5N8MqwvVvmqwsD4-vgUoLqSRg','AIzaSyBNiTP5dvW_2FS_vSr89oU0Q8Wc-lhzfjs','AIzaSyCjTjiBfYyUzHQDr8-PIO5KF3XvVu6wNjo','AIzaSyCJPRL3K_w3l_DtoM0Xhpv2KrKVWlQfuAo','AIzaSyDcBHi3Cs0n4QsSOhl6K5fiRkKV9gif2h4','AIzaSyDpbFkJanVQNsUekdg3Josx_3j226Pkgqo','AIzaSyB1l0hL8-YM2A1FCeZIJfb8nQY2hlgn51I','AIzaSyBH4OukzwdQKOQD_PK9ZtGRqqx9twsVdm0']
    R=6373
    '''from_res = input("Enter the starting restaurant:-")
    to_res = input("Enter upto how many restaurant u wan't to see:-")'''
    path = "C:\Users\Jayant\Desktop\Tomato\Tomato_db_sorted.csv"
    #My Location : 22.587212, 88.374389
    #gmaps = googlemaps.Client(key='AIzaSyAMdDIbyp5N8MqwvVvmqwsD4-vgUoLqSRg')
    my_loc = (22.587212, 88.374389)
    res_loc,xy = get_loc(path)
    G=nx.Graph()
    for zone,num in zip(zones[7:8],xrange(len(zones[7:8]))):
        num=7
        print "Fetching graph of Zone_%d"%num
        gmaps = googlemaps.Client(key=keys[num])
        G.add_node("Zone_%d_%s"%(num,str(zone)),pos=zone)
        c=1
        res=1
        node_hash = {}
        for loc in xy[1:5]:
            print res
            try:
                location = get_directions(zone,loc)
            except:
                print loc
            nodes = [["Zone_%d_%s"%(num,str(zone)),zone]]
            for locs in location[1:-1]:
                node = str(locs)
                '''node = get_address(locs)
                if c not in nodes:
                    G.add_node(c,pos=locs)
                nodes.append(c)
                c=c+1'''
                if not G.has_node(node):
                    G.add_node(node,pos=locs)
                nodes.append([node,locs])
            G.add_node("Res#%d%s"%(res,loc),pos=loc)
            nodes.append(["Res#%d%s"%(res,loc),loc])
            res+=1
            for i in xrange(1,len(nodes)):
                if G.has_edge(nodes[i-1][0],nodes[i][0]):
                    wt=G[nodes[i-1][0]][nodes[i][0]]['weight']
                else:
                    wt=0
                G.add_edge(nodes[i-1][0],nodes[i][0],weight=wt+1)
                #G.add_edge(nodes[i-1][0],nodes[i][0],weight=findDistance(nodes[i-1][1][0],nodes[i][1][0],nodes[i-1][1][1],nodes[i][1][1]))
    pos = nx.get_node_attributes(G,'pos')
    #print pos
    nx.draw(G,pos)
    plt.show()
    #print_edge(G)
    save_edgelist(G) 
Example 44
Project: PoGoMap-GUI   Author: engle2192   File: utils.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def set_config(root_path):
	config['ROOT_PATH'] = root_path
	configpath = get_path('config/config.ini')
	parser = configargparse.ArgParser(default_config_files=[configpath])
	parser.add_argument('-H', '--host', help='Set web server listening host', default='127.0.0.1')
	parser.add_argument('-P', '--port', type=int, help='Set web server listening port', default=4000)
	parser.add_argument('-k', '--key', help='Specify a Google Maps API Key to use.')
	parser.add_argument('-c', '--config', help='Alarms configuration file. default: alarms.json', default='alarms.json')
	parser.add_argument('-l', '--location', type=parse_unicode, help='Location, can be an address or coordinates')
	parser.add_argument('-L', '--locale', help='Locale for Pokemon names: default en, check locale folder for more options', default='en')
	parser.add_argument('-u' , '--units',  help='Specify either metric or imperial . Default: metric', choices=['metric', 'imperial'], default='metric')
	parser.add_argument('-d', '--debug', help='Debug Mode', action='store_true',  default=False)
	parser.add_argument('-gf', '--geofence', help='Specify a file of coordinates, limiting alerts to within this area')
	parser.add_argument('-tl', '--timelimit', type=int, help='Minimum number of seconds remaining on a pokemon to notify', default=0)
	parser.add_argument('-tz', '--timezone', help='Timezone used for notifications.  Ex: "America/Los_Angeles"')
	
	args = parser.parse_args()
	
	config['HOST'] = args.host
	config['PORT'] = args.port
	config['CONFIG_FILE'] = args.config
	config['LOCALE'] = args.locale
	config['DEBUG'] = args.debug
	config['UNITS'] = args.units
	config['TIME_LIMIT'] = args.timelimit
	
	if args.key:
		config['API_KEY'] = key=args.key
		config['GMAPS_CLIENT'] = googlemaps.Client(key=args.key)
	
	if args.location:
		config['LOCATION'] =  get_pos_by_name(args.location)
	
	if args.geofence:
		config['GEOFENCE'] = Geofence(os.path.join(root_path, args.geofence))

	if args.timezone:
		try:
			config['TIMEZONE'] = pytz.timezone(args.timezone)
			log.info("Timezone set to: %s" % args.timezone)
		except pytz.exceptions.UnknownTimeZoneError:
			log.error("Invalid timezone. For a list of valid timezones, see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
			sys.exit(1)

	config['REV_LOC'] = False
	config['DM_WALK'] = False
	config['DM_BIKE'] = False
	config['DM_DRIVE'] = False
	
	return config

#Returns +inf if True, else float, else None