예제 #1
0
	def user_address_details(user_address):
		client = Client(key = "AIzaSyCukzR1OSSqPFI9uI50_XzAZs7F_EQUT1M")
		listy = []
		# exactaddress ="1 Toronto Street Toronto"
		# cor = client.geocode(exactaddress)
		cor = client.geocode(user_address)
		# listy= cor[0]['geometry']['location'][0],cor[0]['geometry']['location'][1]
		# print listy
		return cor[0]['geometry']['location']['lat'],cor[0]['geometry']['location']['lng']
예제 #2
0
    def __init__(self, api_key, logger=None):
        '''
        location management

        :param api_key: google maps api key
        '''
        # see https://developers.google.com/maps/documentation/elevation/usage-limits
        # used for google maps geocoding
        self.gmapsclient = Client(key=api_key, queries_per_second=50)

        self.logger = logger
def gmapcalc(location1, location2, apiuse):
    api_key = 'AIzaSyAn6U1F6NJIJx226L8sK5my_ECvHm7k18o'
    gmaps = Client(api_key)
    data = distance_matrix(gmaps, location1, location2)
    timeaway = data['rows'][0]['elements'][0]['duration']['text']
    global apiusecounter
    apiusecounter += 1
    return (timeaway)
예제 #4
0
    def __init__(self, key, route=None):
        """
        A class for parsing the directions built by the CitiesForm, getting a valid route and then tranforming that route
        so it can be re-rendered by the javascript maps api

        :param key: a google maps api secret access key
        :param route: the route from the CitiesForm
        """
        self._client = Client(key)
        self._route = route
        self._params = None
        self.directions = None

        if route is not None:
            self._parse_route()

            self.get_directions()
예제 #5
0
SHEETS_SERVICE = 'sheets'
SHEETS_VERSION = 'v4'
DRIVE_SERVICE = 'drive'
DRIVE_VERSION = 'v3'

APP_CRED_FOLDER = app.config['APP_CRED_FOLDER']
APP_EARTH_RADIUS = app.config['APP_EARTH_RADIUS']
geodist = GeoDistance(APP_EARTH_RADIUS)

debug = False

idlocker = RLock()
# see https://developers.google.com/maps/documentation/elevation/usage-limits
# also used for google maps geocoding
gmapsclient = Client(key=app.config['GMAPS_ELEV_API_KEY'],queries_per_second=50)

# configuration
## note resolution is about 9.5 meters, so no need to have points
## closer than within that radius
FT_PER_SAMPLE = 60 # feet
MAX_SAMPLES = 512

# calculated
MI_PER_SAMPLE = FT_PER_SAMPLE / 5280.0
SAMPLES_PER_MILE = 5280 / FT_PER_SAMPLE # int
GELEV_MAX_MILES = MAX_SAMPLES*1.0 / SAMPLES_PER_MILE

class GoogleApiError(Exception): pass
class IdNotFound(Exception): pass
예제 #6
0
import gspread
import json
import random
import geocoder
import os
import time
import collections as co
from googlemaps.client import Client
from googlemaps.distance_matrix import distance_matrix

api_key = 'AIzaSyA47CBshq2fOEMhtM15Mu7jj9QJ5O47YxU'
gmaps = Client(api_key)
from oauth2client.service_account import ServiceAccountCredentials


def send_id(email, id_num):
    # import the smtplib module. It should be included in Python by default
    import smtplib
    # set up the SMTP server
    s = smtplib.SMTP(host='smtp.gmail.com', port=587)
    s.starttls()
    pass1 = open('/home/kde-ronz/Public/credentials.txt', 'r')
    pass2 = pass1.read()
    MY_ADDRESS, PASSWORD = pass2.split()
    s.login(MY_ADDRESS, PASSWORD)

    # import necessary packages
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    # For each contact, send the email:
		c=input()
		if(c==1):
			prevquestions.append(nextquestion)
		else:
			regectedquestions.append(nextquestion)
			continue
	disease=find_disease(prevquestions)
	print "The diagised disease based on the questions is ",diseasenames[disease]
def summary(disease):
	return wikipedia.summary(disease,sentences=3)
def getlocation():
	url = 'http://ipinfo.io/json'
	response = urlopen(url)
	data = json.load(response)
	return map(float,data['loc'].split(','))
client=Client(key='AIzaSyCI3v6QCJQGStSjCIsIntZht_9gfSdism4')
client2=Client(key="AIzaSyA33TOQQggSGj--2pKHiEK2X996VyjG8h8")
def gethospitals():
	places=places_nearby(client,getlocation(),keyword="Hospitals near me",open_now=True,rank_by='distance',type="hospital")
	hospitals=[]
	for hospital in places['results']:
		name=hospital['name']
		if not 'Vetenary' in name:
			if not "Critical" in name:
				if not "Neuro" in name:

					hospitals.append(name)
	#return hospitals
	hospitaldistances={}
	for name in hospitals:
		hospitaldistances[name]=distance_matrix(client2,[tuple(getlocation())],name)['rows'][0]['elements'][0]['distance']['text']
예제 #8
0
def googlemap_drive_duration(startPoint, endPoint, startYear, startMonth, startDay, startHour, startMinute, total_num, API_keys):
	
	day = DateChecker.func( startYear, startMonth, startDay )

	if int(startMonth) != 12:
		num_day_2018 = (date(2018, int(startMonth) + 1, 1) - date(2018, int(startMonth), 1)).days
		num_day_2017 = (date(2017, int(startMonth) + 1, 1) - date(2017, int(startMonth), 1)).days
	else:
		num_day_2018 = (date(2019, 1, 1) - date(2018, 12, 1)).days
		num_day_2017 = (date(2018, 1, 1) - date(2017, 12, 1)).days
		
	day_count_2018 = 0
	day_count_2017 = 0
	temp_2018 = []
	temp_2017 = []
	for j in range(num_day_2018):
		if DateChecker.func( 2018, int(startMonth), j + 1 ) == day:
			temp_2018.append( [] )
			temp_2018[day_count_2018].append(2018)
			temp_2018[day_count_2018].append(int(startMonth))
			temp_2018[day_count_2018].append(j + 1)
			day_count_2018 += 1
		else:
			pass
	week_num = 0	
	for j in range(num_day_2017):
		if DateChecker.func( 2017, int(startMonth), j + 1 ) == day:
			if j + 1 == int(startDay):
				week_num = day_count_2017 + 1
			else:
				pass
			temp_2017.append( [] )
			temp_2017[day_count_2017].append(2017)
			temp_2017[day_count_2017].append(int(startMonth))
			temp_2017[day_count_2017].append(j + 1)
			day_count_2017 += 1
		else:
			pass
	
	if day_count_2018 < day_count_2017:	
		startDay_2018 = temp_2018[week_num - 1][2]
	else:	
		startDay_2018 = temp_2018[week_num][2]

	startPoint = "Divvy Station: " + startPoint
	endPoint = "Divvy Station: " + endPoint
	departureDate = datetime(int(2018), int(startMonth), int(startDay_2018), int(startHour), int(startMinute), 0, 0)
	departureDate.isoformat()
	gmaps = Client(api_key)
	data = distance_matrix(gmaps, startPoint, endPoint, "driving", departure_time = departureDate)
	try:
		driving_duration = data['rows'][0]['elements'][0]['duration']['text']
		driving_duration_in_traffic = data['rows'][0]['elements'][0]['duration_in_traffic']['text']
		driving_distance = data['rows'][0]['elements'][0]['distance']['text']
		print (driving_distance)
	except KeyError:
		print ( data )
		driving_duration = str(0) + " mins"
		driving_duration_in_traffic = str(0) + " mins"
		driving_distance = str(0) + " km"
	google_API_data = [driving_duration, driving_duration_in_traffic, driving_distance, data]
	return google_API_data				
import json
import random

from googlemaps.client import Client
from googlemaps.distance_matrix import distance_matrix
api_key = 'AIzaSyA47CBshq2fOEMhtM15Mu7jj9QJ5O47YxU'
gmaps = Client(api_key)

a = [{
    "location_id": "387",
    "zone_id": "11",
    "name": "Aundh ",
    "latitude": "18.558",
    "longitude": "73.8075",
    "city_id": "2",
    "code": "",
    "pincode": "411007"
}, {
    "location_id": "312",
    "zone_id": "10",
    "name": "Aundh Camp ",
    "latitude": "18.5552",
    "longitude": "73.8189",
    "city_id": "2",
    "code": "",
    "pincode": "411027"
}, {
    "location_id": "388",
    "zone_id": "11",
    "name": "Aundh",
    "latitude": "18.558",
예제 #10
0
 def __init__(self, ApiKey, language):
     self._client = Client(ApiKey)
     self._language = language
     BodyMaps.__init__(self)
예제 #11
0
파일: main.py 프로젝트: vovani/retail-route
from collections import defaultdict
from lxml import etree

from parse import parse_stores, fetch_stores, parse_price, parse_promo, unique_id
from route import find_route, cheapest

if __name__ == '__main__':
    dir = '/mnt/c/Work/PharmTraverse/Data'
    ff = glob(dir + '/*/*.xml')
    prices_filenames = np.array(filter(lambda f: 'price' in f.lower(), ff))
    promos_filenames = filter(lambda f: 'promo' in f.lower(), ff)
    store_filenames = filter(lambda f: 'store' in f.lower(), ff)
    print len(prices_filenames)
    print len(promos_filenames)
    print len(store_filenames)
    c = Client(key='AIzaSyBsOohh5S08mhOmKT00ncWtFUBJXddhRvg')
    if os.path.exists('/mnt/c/Work/PharmTraverse/Data/stores.json'):
        stores_raw = json.load(
            open('/mnt/c/Work/PharmTraverse/Data/stores.json'))
    else:
        stores_raw = {}
        for store_filename in store_filenames:
            store_name = os.path.basename(os.path.dirname(store_filename))
            print store_filename
            print store_name
            new_stores = parse_stores(c, store_filename, store_name)
            stores_raw.update({
                sid: {
                    'lat': p[0].latitude,
                    'lon': p[0].longitude,
                    'addr': p[1]
예제 #12
0
class GmapsLoc():
    # ----------------------------------------------------------------------
    def __init__(self, api_key, logger=None):
        '''
        location management

        :param api_key: google maps api key
        '''
        # see https://developers.google.com/maps/documentation/elevation/usage-limits
        # used for google maps geocoding
        self.gmapsclient = Client(key=api_key, queries_per_second=50)

        self.logger = logger

    # ----------------------------------------------------------------------
    def loc2latlng(self, loc):
        '''
        convert location to (lat, lng)

        :param loc: location address or string 'lat, lng'
        :return: [float(lat), float(lng)]
        '''

        ## if 'lat, lng', i.e., exactly two floating point numbers separated by comma
        try:
            checkloc = loc.split(', ')
            if len(checkloc) != 2: raise ValueError
            latlng = [float(l) for l in checkloc]

        ## get lat, lng from google maps API
        except ValueError:
            if self.logger:
                self.logger.debug('snaploc() looking up loc = {}'.format(loc))
            # assume first location is best
            geoloc = self.gmapsclient.geocode(loc)[0]
            lat = float(geoloc['geometry']['location']['lat'])
            lng = float(geoloc['geometry']['location']['lng'])
            latlng = [lat, lng]

        return latlng

    def get_location(self, location, loc_id, cache_limit):
        '''
        get current lat, lng for location, update cache if needed

        caller must verify location text is the same. If not the loc_id should
        be deleted first and loc_id=None should be passed in to create a new
        Location record.

        :param location: text location
        :param loc_id: possible location id, may be 0 or null if not set yet
        :param cache_limit: number of days in cache before needs to be recached
        :return: {'id': thisloc.id, 'coordinates': [thisloc.lat, thisloc.lng]}
        '''
        # check location for lat, lng
        # check for lat, long
        geoloc_required = True
        if isLatlng(location):
            geoloc_required = False
            checkloc = location.split(',')
            lat = float(checkloc[0].strip())
            lng = float(checkloc[1].strip())

        # loc_id may be 0 or null, meaning the location isn't set
        if not loc_id:
            thisloc = Location(location=location,
                               geoloc_required=geoloc_required)
            db.session.add(thisloc)
            # check for lat, long
            if not geoloc_required:
                thisloc.lat = lat
                thisloc.lng = lng

        # loc_id was set, get the record
        else:
            thisloc = Location.query.filter_by(id=loc_id).one()

        if not thisloc.geoloc_required:
            # save everything and return the data
            db.session.commit()
            return {
                'id': thisloc.id,
                'coordinates': [thisloc.lat, thisloc.lng]
            }

        # if we reach here, cache check is required
        now = datetime.now()

        # if we need to reload the cache, do it
        if not thisloc.cached or (now -
                                  thisloc.cached) > timedelta(cache_limit):
            thisloc.cached = now
            geoloc = self.gmapsclient.geocode(location)[0]
            lat = float(geoloc['geometry']['location']['lat'])
            lng = float(geoloc['geometry']['location']['lng'])
            thisloc.lat = lat
            thisloc.lng = lng

        # save everything and return the data
        db.session.commit()
        return {'id': thisloc.id, 'coordinates': [thisloc.lat, thisloc.lng]}

    def check_location(self, location):
        try:
            geoloc = self.gmapsclient.geocode(location)
            if len(geoloc) > 0:
                return True
            else:
                return False
        except:
            return False
예제 #13
0
 def __init__(self, config: Dict):
     self.config: GoogleAPIConfig = GoogleAPIConfig(
         **config[self.config_key], )
     self.client: Client = Client(self.config.api_key)
예제 #14
0
Created on Fri Jul 27 22:44:01 2018

@author: matthewszhang
"""
import os
import os.path as osp
import numpy as np
import glob
import shutil

from adrenalan.classification import setup, dynamic_run
from googlemaps.client import Client
import googlemaps.places as Places

KEY = 'AIzaSyBwj6mhh8CdAixwINve65aCmvxKJTuBLoM'
CLIENT = Client(KEY)
RADIUS = 100
MAXIMG = 3


def get_nearby_locations(coordinates, **kwargs):
    assert isinstance(coordinates, tuple)
    results = Places.places_nearby(CLIENT, coordinates, RADIUS, **kwargs)
    return results['results']


def write_picture(ret, name, iteration=0, tempdir='tmp'):
    tempdir = osp.join(os.getcwd(), tempdir)
    if not osp.exists(tempdir):
        os.makedirs(tempdir)
    f = open(
예제 #15
0
#
#   Duraction
#
#   A service to provide duration when given a direction and an endpoint
#
from config import api_key, place_ids
import googlemaps
from googlemaps.client import Client

#   Query google servers for route
client = Client(api_key)
params = {
    'origin': 'place_id:' + place_ids['home'],
    'destination': 'place_id:' + place_ids['tigo'],
    'departure_time': 'now',
}
directions = client._get('/maps/api/directions/json', params)

#   Parse out route summary
duration = directions['routes'][0]['legs'][0]
summary = directions['routes'][0]['summary']

#   Prase out route duration
route = directions['routes'][0]['legs'][0]
minutes = route['duration_in_traffic']['text']

#   Output route message
print('Suggested Route: ' + summary)
print(minutes)
예제 #16
0
from googlemaps.client import Client
from googlemaps.distance_matrix import distance_matrix

from duration_auth import (apiKey)

gmaps = Client(apiKey)
data = distance_matrix(gmaps, "55.781121, -4.045619", "56.454346, -3.016491")
duration = data['rows'][0]['elements'][0]['duration']['text']
print(duration)