def tw_expert_location_geocoding(self, tw_user_location):
        """
        Using data from the <tw_location> field in <monexp_db> database, 
        and python-gmaps Package as wrapper for Google Maps Geocoding API (as part of Google Maps API),
        get the latitude and longitude of the expert's location

        Arguments:
            tw_user_location {str} -- The value of the <tw_user_location> field 
                                      of the User object in Twitter
        
        Returns:
            [float] -- latitude of the expert's location or None, if the latitude was not determined
            [float] -- longitude of the expert's location or None, if the longitude was not determined
        """

        try:
            gmaps_request = Geocoding(api_key='<your-api_key>')
            gmaps_result = gmaps_request.geocode(tw_user_location)
            expert_location_lat = gmaps_result[0]['geometry']['location'][
                'lat']
            expert_location_lng = gmaps_result[0]['geometry']['location'][
                'lng']

        except:
            expert_location_lat = None
            expert_location_lng = None

        return expert_location_lat, expert_location_lng
Esempio n. 2
0
def geocode(address, api_key=None):

    api_key = getattr(settings, 'WORKON_GOOGLE_API_KEY', api_key)
    if api_key and api_key.strip() == "":
        api_key = None

    api = Geocoding(api_key=api_key)
    if address.strip() != '':
        original_address = address.strip()
        try:

            latlng = latlngreg.search(original_address)
            if latlng:
                results = api.reverse(float(latlng.group(1)),
                                      float(latlng.group(2)))
            else:
                results = api.geocode(original_address)

            if len(results):
                results[0]['lng'] = results[0].get('geometry', {}).get(
                    'location', {}).get('lng', None)
                results[0]['lat'] = results[0].get('geometry', {}).get(
                    'location', {}).get('lat', None)
                return results[0]

        except NoResults, e:
            return {'error': 'NoResults', 'message': str(e.message)}
        except GmapException, e:
            return {'error': 'GmapException', 'message': str(e.message)}
Esempio n. 3
0
def index(request):
    consumer_key = "YAvBBJnUpgMOWIkBbzjjsCy1q"
    consumer_secret = "xPcvMjYjSicdIIcC57E9M8X51sarSiSi3syNjNZpNHn9wbz9gd"
    access_token = "841688184467705856-Sm1KiDoZomcOHgsXvJWj9ifXsHR5nc9"
    access_token_secret = "IhAGMDIfLn5eWvhUQVFvhqnYZ48q6c9VGZH735a43F3AZ"

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)

    word = request.GET.get("word", None)

    public_tweets = api.search(str(word), retry_count=3, count=50)

    api1 = Geocoding()
    lat1 = dict(api1.geocode("new york")[0])['geometry']['location']['lat']
    lng1 = dict(api1.geocode("new york")[0])['geometry']['location']['lng']
    map_osm = folium.Map(location=[lat1, lng1], zoom_start=3)

    for tweet in public_tweets:

        analysis = textblob.TextBlob(tweet.text)
        a = tweet.user.location
        try:

            if a == '' or len(a) >= 12 or len(a) <= 3 or textblob.TextBlob(
                    a).detect_language() != 'en' or a == 'interwebs':
                lat = random.uniform(30, 60)
                lng = random.uniform(-135, -75)
            else:
                lat = dict(api1.geocode(a)[0])['geometry']['location']['lat']
                lng = dict(api1.geocode(a)[0])['geometry']['location']['lng']

            if analysis.sentiment[0] > 0:
                folium.Marker([lat, lng],
                              popup=str(analysis.sentiment) + "location:" +
                              str(a) + "latitude:" + str(round(lat, 2)) +
                              "longitude:" + str(round(lng, 2)),
                              icon=folium.Icon(color='green')).add_to(map_osm)
            elif analysis.sentiment[0] == 0:
                folium.Marker([lat, lng],
                              popup=str(analysis.sentiment) + "location:" +
                              str(a) + "latitude:" + str(round(lat, 2)) +
                              "longitude:" + str(round(lng, 2)),
                              icon=folium.Icon(color='blue')).add_to(map_osm)
            elif analysis.sentiment[0] < 0:
                folium.Marker([lat, lng],
                              popup=str(analysis.sentiment) + "location:" +
                              str(a) + "latitude:" + str(round(lat, 2)) +
                              "longitude:" + str(round(lng, 2)),
                              icon=folium.Icon(color='red')).add_to(map_osm)
        except:
            pass
        map_osm.save('blog2/templates/blog2/osm.html')

    return render(request, "blog2/osm.html")
Esempio n. 4
0
    def look_uber(self, source, destination, cab_type, intent):
        api = Geocoding()
        try:
            source_loc = api.geocode(source)
            source_lat_long = source_loc[0]['geometry']['location']
            start_lat = source_lat_long['lat']
            start_lng = source_lat_long['lng']
        except:
            return 'Enter Valid Source.\n'

        try:
            destination_loc = api.geocode(destination)
            destination_lat_long = destination_loc[0]['geometry']['location']
            end_lat = destination_lat_long['lat']
            end_lng = destination_lat_long['lng']
        except:
            return 'Enter Valid destination.\n'

        try:
            response = client.get_price_estimates(start_latitude=start_lat,
                                                  start_longitude=start_lng,
                                                  end_latitude=end_lat,
                                                  end_longitude=end_lng,
                                                  seat_count=2)

            estimate = response.json

            for cab_types in estimate['prices']:
                if cab_types['localized_display_name'].lower(
                ) == cab_type.lower():
                    if (intent == 'book'):
                        out = 'Booking ' + (
                            cab_type) + ' with averege fare ' + (
                                cab_types['estimate']
                            ) + '. Your journy will be ' + str(
                                cab_types['distance']
                            ) + ' KM long and will take ' + str(
                                cab_types['duration'] / 60) + ' minutes. '
                        return out + self.cab_details()
                    else:
                        out = str(cab_type) + ' with averege fare ' + (
                            cab_types['estimate']
                        ) + 'is available. Distance will be ' + str(
                            cab_types['distance']
                        ) + ' KM and it will take ' + str(
                            cab_types['duration'] / 60) + ' minutes.'
                        print(out)
                        return str(out)
        except uber_error.ClientError as e:
            return 'Distance between two points exceeds 100 miles'
Esempio n. 5
0
 def test_json_like_geocode_call(self):
     gmaps_api = Geocoding(
         **{
             'sensor': True,
             'use_https': True,
             'api_key': u'{}'.format(settings.GMAPS_API_KEY)
         })
     california = GmapsItem.objects.get(short_name="CA")
     california_response = california.get_response_json()
     geocode_response = gmaps_api.reverse(
         float(california.lat), float(california.lng), **{
             'language': 'en',
             'result_type': ['administrative_area_level_1']
         })
     self.assertEqual(california_response, json.dumps(geocode_response[0]))
Esempio n. 6
0
def get_zip(loc):
    try:
        latitude = loc[0].get('data-latitude')
        longitude = loc[0].get('data-longitude')
        google_api = Geocoding('AIzaSyBkWTcFg-kawvHmt1MryKvMcpmsNmrGWPU')
        map_loc = google_api.reverse(float(latitude), float(longitude))
        items = map_loc[0]['address_components']
        result = [
            item['long_name'] for item in items
            if item['types'][0] == 'postal_code'
        ]
        code = 'USA-' + result[0]
        return code
    except IndexError:
        return None
Esempio n. 7
0
def look_uber(source,destination=None):
    api = Geocoding()
    try:
        source_loc = api.geocode(source)
        source_lat_long = source_loc[0]['geometry']['location']
        start_lat=source_lat_long['lat']
        start_lng=source_lat_long['lng']
    except:
        print('Enter Valid Source.\n')
        print('Please let me know if you want to know anything more')
        return('null')
    
    
    if destination : 
        try:
            destination_loc = api.geocode(destination)
            destination_lat_long = destination_loc[0]['geometry']['location']
            end_lat=destination_lat_long['lat']
            end_lng=destination_lat_long['lng']

        except:
            print('Enter Valid destination.\n')
            print('Please let me know if you want to know anything more')
            return('null')
        
    else:
        end_lat=12.9173312 # latitude of Central Silk Board
        end_lng=77.6212483 # longitude of Central Silk Board
    try:
        response = client.get_price_estimates(
            start_latitude=start_lat,
            start_longitude=start_lng,
            end_latitude=end_lat,
            end_longitude=end_lng,
            seat_count=2
            )    

        estimate = response.json 
        cab_details_df= uber_cab_details(estimate)
        cab_details_df.fillna(0, axis=1, inplace=True)
        #print('Following are the cabs availability\n')
        #print(cab_details_df)
        return cab_details_df
    except uber_error.ClientError as e:
        print('Distance between two points exceeds 100 kms\n')
        print('Please let me know if you want to know anything more')
        return('null')
Esempio n. 8
0
 def geo(self, search):
     """
     Get a dict_location from gmaps.
     :param search:
     :return: dict_location
     """
     try:
         gmaps = Geocoding(api_key=MAP_API_KEY)
         geocode_result = gmaps.geocode(search, language='fr')[0]
         dict_location = {}
         for libelle, item in geocode_result.items():
             if libelle == 'formatted_address':
                 dict_location['adresse'] = item
             elif libelle == 'geometry':
                 dict_location['latitude'] = item['location']['lat']
                 dict_location['longitude'] = item['location']['lng']
         return dict_location
     except:
         return False
#use python_gmaps module
#Many online providers such as Google & Bing have geocoding services
#Here is a code to get a Lat & Lng from Google
import sys
from gmaps import Geocoding

#create api_key using => https://developers.google.com/maps/documentation/geocoding/start
#api = Geocoding(api_key='Your API_KEY')

api = Geocoding(api_key='AIzaSyBGJgF7gltKbGbyEdio03s5vmYoIc6Uww8')

#find entered loctaion using api geocode
geofind = api.geocode(sys.argv[1])
geofind[0]
print(geofind[0]['geometry']['location'])
Esempio n. 10
0
from multiprocessing import Pool

from gmaps import Geocoding

api = Geocoding()


PLACES = (
    'Reykjavik', 'Vien', 'Zadar', 'Venice',
    'Wrocław', 'Bolognia', 'Berlin', 'Słubice',
    'New York', 'Dehli',
)

POOL_SIZE = 4


def fetch_place(place):
    return api.geocode(place)[0]


def present_result(geocoded):
    print("{:>25s}, {:6.2f}, {:6.2f}".format(
        geocoded['formatted_address'],
        geocoded['geometry']['location']['lat'],
        geocoded['geometry']['location']['lng'],
    ))


def main():
    with Pool(POOL_SIZE) as pool:
        results = pool.map(fetch_place, PLACES)
from gmaps import Geocoding
from gmaps import errors
import sys

geo = Geocoding(api_key="AIzaSyCAU19MydrGYH5TulC8jFS9EYv8EiYLegY")

address = "".join(sys.argv[1:])
place = geo.geocode(address)[0]
print(place["place_id"] + "\t" + str(place["geometry"]["location"]["lat"]) +
      "\t" + str(place["geometry"]["location"]["lng"]))
Esempio n. 12
0
# エキスパートPythonプログラミング 改訂2版 13章
# マルチスレッドその2
# ワーカースレッド内で発生した例外をメインスレッドに返す

import time
from gmaps import Geocoding
from threading import Thread, current_thread
from queue import Queue, Empty
from util import PLACES, get_config

api = Geocoding(api_key=get_config()["geocode_api_key"])


def fetch_place(place):
    geocoded = api.geocode(place)[0]
    return geocoded, current_thread().name


def present_result(geocoded, thread_name):
    print(
        f'{geocoded["formatted_address"]:>60s}, {geocoded["geometry"]["location"]["lat"]:6.2f}, {geocoded["geometry"]["location"]["lng"]:6.2f} [{thread_name}]'
    )


def worker(work_queue, results_queue):
    # 各々のスレッドは、work_queue から取り出して処理する
    # どの都市をどのスレッドが処理するかは、その時次第
    while not work_queue.empty():
        try:
            item = work_queue.get(block=False)
        except Empty:
Esempio n. 13
0
"""
Main backend file for SmartPark project.
Created by:
Yosef Leibman
Abhishek Kapoor
Sultan Sidhu
for TD Bank Elevate Hackathon, 22 September 2018.
"""
from gmaps import Geocoding
from json import JSONDecoder
import json

instance = Geocoding(api_key="<your api key>")  # todo: read api key from a txt file.
file = open("/Users/sultansidhu/Desktop/DataFiles/greenPParking2015.json")
stuff = file.read()
jsonstuff = json.loads(stuff)
# for x in jsonstuff['carparks']:
#     print(x, end="\n\n\n\n\n")


class ParkingClass:

    def __init__(self, location: tuple, address: str, rate_per_half_hour: float, capacity: int):
        """
        Creates a new Parking object
        """
        self.location = location
        self.address = address
        self.rate_per_hour = rate_per_half_hour
        self.capacity = capacity
        self.proximity_rating = 0
Esempio n. 14
0
# -*- coding: utf-8 -*-
import pytest
from gmaps import errors

from gmaps import Geocoding
from .testutils import retry

geocoding = Geocoding(sensor=False)


@retry
def test_geocode():
    results = geocoding.geocode(u"Wrocław, Hubska")
    assert results
    assert len(results) > 0


@retry
def test_geocode_override_sensor():
    results = geocoding.geocode(u"Wrocław, Hubska", sensor=True)
    assert results
    assert len(results) > 0


@retry
def test_geocode_components_filters():
    """Test if querying with same route but different component filtering
    returns different locations"""
    # both these cities has this street
    results1 = geocoding.geocode(u"Łubinowa",
                                 components={"locality": "Wrocław"})
Esempio n. 15
0
from gmaps import Geocoding
from gmaps import Directions
import gmaps
import pprint
import re

direct = Directions()
geo = Geocoding()

TAG_RE = re.compile(r'<[^>]+>')
startLoc = '2121 S. El Camino Real, San Mateo CA'
endLoc = '820 E El Camino Real, Mountain View, CA'
DEFAULT = 'Hollingsworth Drive, Mountain View CA'
token = '\n'


def remove_tags(text):
    return TAG_RE.sub('', text)


# supported modes include driving, walking, bicycling, transit
def get_directions(start, end, transport="driving"):
    try:
        direct = Directions()
        response = direct.directions(start, end, mode=transport)
    except gmaps.errors.GmapException as ex:
        response = '1'
    except:
        response = '2'
    return response
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr  1 16:58:12 2018

@author: josephuses
"""

#!/usr/bin/env python
import pandas as pd
from gmaps import Geocoding
# Use your own api key by registering at https://console.cloud.google.com/apis/credentials?project=starlit-woods-175707
api = Geocoding(api_key = 'Your api key')

# import the data
data = pd.read_csv("data.csv")
# make a list of the addresses in data['address']
# change the index as desired
# remember that you are only limited to 2500 queries in a day
address = data['address'][:1000].tolist()
# initialize the location list
location = []
# Download the geocodes for each school address
for place in address:
    try:
        location.append(api.geocode(place))
    except Exception as e:
        location.append("No Result")

# Initialize the lat (latitude) and long (longitude) lists
lat = []
Esempio n. 17
0
ALLOWED_TYPES = settings.GMAPS_PLACES_ALLOWED_TYPES
URL_TYPES = settings.GMAPS_PLACES_URL_TYPES
GMAPS_DEFAULT_CLIENT_PARAMS = {
    'sensor': False,
    'use_https': True,
    'api_key': settings.GMAPS_API_KEY,
}
GMAPS_DEFAULT_GEOCODE_PARAMS = {
    'language': settings.GMAPS_LANGUAGE_CODE,
    # 'region': settings.GMAPS_REGION, TODO
}
GMAPS_DEFAULT_REVERSE_PARAMS = {
    'language': settings.GMAPS_LANGUAGE_CODE,
}
gmaps_api = Geocoding(**GMAPS_DEFAULT_CLIENT_PARAMS)


class gmaps_attempt(object):
    def __init__(self, gmaps_call):
        self.gmaps_call = gmaps_call

    def __call__(self, *args, **kwargs):
        attempts = 0
        success = False
        while success is not True and attempts < 3:
            attempts += 1
            try:
                result = self.gmaps_call(*args, **kwargs)
            except (NoResults, RequestDenied, InvalidRequest) as e:
                raise e
def __process_extracted_data(results, restaurant, state, extractedDataFile, namesAllowed):
	"""
	This function processes the extracted data using pandas and stores the location density in a csv file

	:param: results - list of dictionary of restaurant location data 
	:type: list
	
	:param: restaurant - name of the restaurant; eg. Pizza Hut
	:type: str

	:param: state - name of the state; eg. CA
	:type: str
	
	:param: extractedDataFile - path of the file where the extracted data will be stored
	:type: str

	:param: namesAllowed - names of the restaurant to qualify as valid results; eg. ['Pizza Hut', 'Pizza Hut Express']
	:type: list

	:returns: None
	"""
	
	#assert statements
	assert(isinstance(results, list))
	assert(isinstance(restaurant, str))
	assert(isinstance(state, str))
	assert(isinstance(extractedDataFile, str))
	assert(isinstance(namesAllowed, list))

	df = pd.DataFrame(results)

	#remove restaurants with other name than the restaurant's name
	df = df[df.Name.isin(namesAllowed)]

	#check if the location is within the state
	#get cities name in a list
	citiesFile = f"{FOLDER}/{state}_cities.txt"
	cities = []
	f = open(citiesFile, "r")
	for line in f.readlines():
		cities.append(line.strip().lower())
	f.close()

	geocodeApi = Geocoding(api_key=API_KEY)
	
	for location in set(df['Location']):
		isLocationValid = False
		
		if(not __has_numbers(location) and location.lower() not in cities):
			isLocationValid = False
		elif(not __has_numbers(location) and location.lower() in cities):
			isLocationValid = True
		else:
			try:
				response = geocodeApi.geocode(location + ', ' + state)
				for address in response[0]['address_components']:
					if(address['types'][0] == 'locality'):
						df.replace(location, address['long_name'])
						location =  address['long_name']
					elif(address['types'][0] == 'administrative_area_level_1'):
						isStateValid = address['short_name'] == state
					elif(address['types'][0] == 'country'):
						isCountryValid = address['short_name'] == 'US'

				isLocationValid = isStateValid and isCountryValid
				
			except:
				isLocationValid = False

		if(not isLocationValid):
			df = df[df.Location != location]
	
	#remove duplicate location using dataframes
	df.drop_duplicates(subset=None, keep='last', inplace=True)

	with open(extractedDataFile, 'a', newline="") as csv_file:
		writer = csv.writer(csv_file)
		writer.writerow([restaurant, state, str(len(df))])
Esempio n. 19
0
def test_client_with_key():
    geocoding = Geocoding(api_key="invalid_key", use_https=True)
    with pytest.raises(errors.RequestDenied) as excinfo:
        geocoding.geocode("Some address")

    assert "API key is invalid" in str(excinfo)