Пример #1
0
 def setUp(self):
     self.key = "AIzaasdf"
     self.client = googlemaps.Client(self.key)
Пример #2
0
    waypoint_data = pd.read_csv(file_path, sep="\t")

    for i, row in waypoint_data.iterrows():
        waypoint_distances[frozenset([row.waypoint1,
                                      row.waypoint2])] = row.distance_m
        waypoint_durations[frozenset([row.waypoint1,
                                      row.waypoint2])] = row.duration_s
        all_waypoints.update([row.waypoint1, row.waypoint2])

else:
    #file does not exist - compute results
    print "Collecting Waypoints"
    waypoint_distances = {}
    waypoint_durations = {}

    gmaps = googlemaps.Client(GOOGLE_MAPS_API_KEY)
    for (waypoint1, waypoint2) in combinations(all_waypoints, 2):
        try:
            route = gmaps.distance_matrix(origins=[waypoint1],
                                          destinations=[waypoint2],
                                          mode="driving",
                                          language="English",
                                          units="metric")

            # "distance" is in meters
            distance = route["rows"][0]["elements"][0]["distance"]["value"]

            # "duration" is in seconds
            duration = route["rows"][0]["elements"][0]["duration"]["value"]

            waypoint_distances[frozenset([waypoint1, waypoint2])] = distance
Пример #3
0
# Define api key (automatically get or filled by yourself, see below)
# from GoogleMapsAPIKey import get_my_key
# API_Key = get_my_key()

# ==========================================================
# ==========================================================
# Fill YOUR key get from Google (might change in the future)
API_Key = 'AIzaSyCceg_U0TSY0sASEeVcPV3WXw0NDYHL0j4'
# ==========================================================
# ==========================================================

app = Flask(__name__, template_folder=".")

# Define our client
gmaps = googlemaps.Client(key=API_Key)

# Locate the region (we "FIXED" 40km around JHU here)
location = '39.3299013,-76.6227064'  # coordinate of Johns Hopkins University, Homewood Campus
radius = 40000  # units: meters

# Initialize a set to store types supported by Google Places API
# See documentations in this link (https://developers.google.com/places/web-service/supported_types)
types_set = {
    "accounting", "airport", "amusement_park", "aquarium", "art_gallery",
    "atm", "bakery", "bank", "bar", "beauty_salon", "bicycle_store",
    "book_store", "bowling_alley", "bus_station", "cafe", "campground",
    "car_dealer", "car_rental", "car_repair", "car_wash", "casino", "cemetery",
    "church", "city_hall", "clothing_store", "convenience_store", "courthouse",
    "dentist", "department_store", "doctor", "drugstore", "electrician",
    "electronics_store", "embassy", "fire_station", "florist", "funeral_home",
# Retrieve the road distance from a start and end point
# Using Google's Distance Matrix API

import googlemaps
import config as cfg

gmaps_key = cfg.google['places_key']
gmaps = googlemaps.Client(key=gmaps_key)

def estimate(origin, destination):
    origin_id = 'place_id:' + origin
    destination_id = 'place_id:' + destination
    distance_estimate = gmaps.distance_matrix(
        origins=origin_id,
        destinations=destination_id,
        mode='driving'
    )

    # print(distance_estimate)

    status = distance_estimate['rows'][0]['elements'][0]['status']

    # print(status)

    if status == 'ZERO_RESULTS':
        return 0
    else:
        return distance_estimate['rows'][0]['elements'][0]
Пример #5
0
import smartcar
import googlemaps
from flask import Flask, redirect, request, jsonify, render_template, session
from flask_cors import CORS
from task import Task
from helpers import getVehicleFromId, getAddress, getTime, getDistance, getTimeAt
from datetime import datetime
import time

import os

app = Flask(__name__)
CORS(app)
app.secret_key = 'smartcar'
gmaps = googlemaps.Client(key='AIzaSyChhIkfCNJqOM7QYsBeQmOeG3LKE74RQa4')
start_coords = (43.663040, -79.398010)
# global variable to save our access_token
# access = None
print(os.environ.get('REDIRECT_URI'))

client = smartcar.AuthClient(client_id=os.environ.get('CLIENT_ID'),
                             client_secret=os.environ.get('CLIENT_SECRET'),
                             redirect_uri=os.environ.get('REDIRECT_URI'),
                             scope=[
                                 'read_vehicle_info', 'read_location',
                                 'read_odometer', 'control_security',
                                 'control_security:unlock',
                                 'control_security:lock'
                             ],
                             test_mode=True)
Пример #6
0
import googlemaps

gmaps = googlemaps.Client(key='AIzaSyCJ2GhgOOCaoypV0JCC4NnxS-M0enWpN64')

reverse_geocode_result = gmaps.reverse_geocode((34.852733, -82.3915677))

print(reverse_geocode_result[0]['formatted_address'])

#####################################################################################

geocode_result = gmaps.geocode("650 N Academy St, Greenville, SC 29601, USA")

print(geocode_result[0]['geometry']['location'])
Пример #7
0
import agate
import agateremote
import googlemaps
import datetime

gmaps = googlemaps.Client(key='AIzaSyASamO-yIbsV9Ml6ySteFK12XD2xbleTHU')

def load_year_killed_data(year):
    specified_types = {
        'killed': agate.Number(),
        'injured': agate.Number(),
        'date_hour': agate.Text()
    }
    return agate.Table.from_url('https://s3.amazonaws.com/traffic-sd/accidents_killed_{}.csv'.format(year), column_types=specified_types)


def load_last_fatality():
    return agate.Table.from_url('https://s3.amazonaws.com/traffic-sd/last_fatality.csv')

def load_last_collision():
    return agate.Table.from_url('https://s3.amazonaws.com/traffic-sd/last_collision.csv')

def load_data(data):
    data['table'] = agate.Table.from_url('http://seshat.datasd.org/pd/pd_collisions_datasd.csv')
    return data

def load_all_data_by_year(year):
    data = {}
    data = load_data(data)
    data = add_year_column(data)
    return data['table'].where(lambda r: r['year'] == str(year))
Пример #8
0
def get_graph_from_csv(file_path):

    mdg = nx.DiGraph()
    gmaps = googlemaps.Client(key='AIzaSyBabsATfHAXSihzTwbxTjV9Jqh3MrmZVHs')

    with open(file_path, 'r') as f:
        header_line = f.readline()
        header = {}
        for head in header_line.split(','):
            header[head] = len(header)
        f.readline()  # empty line

        for data_line in f:
            try:
                data = data_line.split(',')
                pickup_longitude = float(data[header['pickup_longitude']])
                pickup_latitude = float(data[header['pickup_latitude']])
                dropoff_longitude = float(data[header['dropoff_longitude']])
                dropoff_latitude = float(data[header['dropoff_latitude']])

                if not (-80.0 < pickup_longitude < -70.0) or \
                        not (35.0 < pickup_latitude < 45.0) or \
                        not (-80.0 < dropoff_longitude < -70.0) or \
                        not (35.0 < dropoff_latitude < 45.0):
                    # print('Skipping line due to strange geo: ' + str(pickup_longitude) + ' '
                    #       + str(pickup_latitude) + ' '
                    #       + str(dropoff_longitude) + ' '
                    #       + str(dropoff_latitude) + ' ')
                    continue

                if False:  # True - use Google; False - hash lat and lng
                    startPointResponce = gmaps.reverse_geocode(
                        (pickup_latitude, pickup_longitude))
                    endPointResponce = gmaps.reverse_geocode(
                        (dropoff_latitude, dropoff_longitude))
                    startPointData = next(iter(startPointResponce), None)
                    endPointData = next(iter(endPointResponce), None)

                    startPointPlaceId = startPointData['place_id']
                    endPointPlaceId = endPointData['place_id']
                else:

                    def my_hash(lat, lng):
                        precision = 3
                        lat_int = int(
                            round(abs(lat), precision) * 10**precision)
                        lng_int = int(
                            round(abs(lng), precision) * 10**precision)
                        hashed = int(str(lng_int) + str(lat_int))
                        return hashed

                    startPointPlaceId = my_hash(pickup_latitude,
                                                pickup_longitude)
                    endPointPlaceId = my_hash(dropoff_latitude,
                                              dropoff_longitude)

                if mdg.has_edge(startPointPlaceId, endPointPlaceId):
                    mdg[startPointPlaceId][endPointPlaceId]['weight'] += 1
                else:
                    mdg.add_edge(startPointPlaceId, endPointPlaceId)
                    mdg[startPointPlaceId][endPointPlaceId]['weight'] = 1
            except ValueError:
                print("Bad line: " + data_line)

    return mdg
# -*- coding: utf-8 -*-
"""However, We found google API charges when there are more than 2500 elements per day. Therefore
we will use R to calculate to distance 
"""
import googlemaps

file = open("INFM600_0201_Fabulous_distance.txt")
result = open("IFNM600_result.txt", "w")

google_api = "AIzaSyDfkpkSBEkcJCk4mGTQ19feimIwm-wh5Vc"

gmaps = googlemaps.Client(key=google_api)

x = gmaps.distance_matrix('New York City', 'Chicago')

for line in file:
    line = line.rstrip()
    llist = line.split()
    startLat = llist[2]
    startLong = llist[3]
    endLat = llist[5]
    endLong = llist[6]
    start = startLat + "," + startLong
    end = endLat + "," + endLong
    gmaps = googlemaps.Client(key=google_api)
    x = gmaps.distance_matrix(start, end)

    for each in x['rows']:
        a = each['elements'][0]
        b = a['distance']
        distance = b['value']
Пример #10
0
import foursquare
import csv
import sys
import subprocess
import googlemaps

from foursquare_secrets import client_id, client_secret
gmaps = googlemaps.Client(key='AIzaSyDSbRjoLe-fnM_NLiQz_yscPNXoEx05vtw')


def get_coordinates(address):
    results = gmaps.geocode(address)
    location = results[0]['geometry']['location']
    return [location['lat'], location['lng']]


# parse command line args
if len(sys.argv) != 2:
    print '''
  Incorrect number of arguments - first argument should be the city name, and the second argument should be the id of the city
  e.g. `python importer.py "London, UK"
  '''
    sys.exit(2)
[_, CITY_NAME] = sys.argv

# geocode the city to get the coordinates
[LAT, LNG] = get_coordinates(CITY_NAME)

# run command to create new city
template_command = """mix CreateCity "{CITY_NAME}" {LAT} {LNG} | grep 'NEW-CITY-ID' | cut -d "'" -f 2"""
CITY_ID = int(
Пример #11
0
        if indicator_list[i] == '0':  # things to do
            places.append(x_coord_list[i] + "," + y_coord_list[i])
            pid[(x_coord_list[i], y_coord_list[i])] = pid_list[i]
            duration.append(60)
        else:
            restaurants.append(x_coord_list[i] + "," + y_coord_list[i])
            pid[(x_coord_list[i], y_coord_list[i])] = pid_list[i]
            duration.append(30)

    # places = ["40.109760744757,-88.227207813792", "310 E Springfield Ave, Champaign, IL",
    #                "406 E Green St, Champaign, IL", "509 E Green St, Champaign, IL",
    #                "1401 W Green St, Urbana, IL", "301 N Neil St, Champaign, IL"]
    #
    # restaurants = ["320 N Chestnut St, Champaign, IL", "60 E Green St, Champaign, IL", "410 E Green St, Champaign, IL", "1214 W University Ave, Urbana, IL"]

    gmaps = gm.Client(key="AIzaSyDRj-IVV1g8aqKOZZiRXyHP4CURyFQg4PQ")
    result = gmaps.distance_matrix(places, restaurants, mode="walking")
    place_to_rest = []
    place_to_rest_time = []
    dist_list = result['rows']
    for li in dist_list:
        rest = []
        time = []
        for dist in li['elements']:
            if (dist['distance']['text'].split(" ")[1] == 'm'):
                rest.append(
                    float(dist['distance']['text'].split(" ")[0]) / 1000)
                time.append(int(dist['duration']['text'].split(" ")[0]))
            else:
                rest.append(float(dist['distance']['text'].split(" ")[0]))
                time.append(int(dist['duration']['text'].split(" ")[0]))
Пример #12
0
    async def extract_lat_long_via_address(self, ctx, *args):

        try:
            # First error check - indicating the user to be more specific so that the search works.

            if (len(args) < 2):

                embed = discord.Embed(title="Nearby Places", color=0xf2680c)
                embed.add_field(
                    name="Error",
                    value=
                    "Please input the command -places followed by a SPACE and the address as specifically as you can. E.G. -places Kaivokatu 1, Helsinki, Finland. This ensures that you get as accurate information as possible.",
                    inline=False)
                # Sending error message.
                await ctx.channel.send(embed=embed)

            else:

                # Splitting the "-places" start-predicative from the actual wanted String.
                address_initial = ' '.join(args)
                # Replacing unwanted characters.
                address_initial = address_initial.replace("ä", "a")
                # Replacing unwanted characters.
                address_initial = address_initial.replace("ö", "o")
                # Splitting the string given, only the address-part remains. E.G. -places Marsinkuja 1, Vantaa => "Marsinkuja 1, Vantaa".
                addressForReplacement = address_initial

                # Error checking for the below IF-clause.
                #address_error_check = addressForReplacement.split(" ")

                if (len(args) < 2 or len(args) < 1):
                    embed = discord.Embed(title="Nearby Places",
                                          color=0xf2680c)
                    embed.add_field(
                        name="Error",
                        value=
                        "Please input the command -places followed by a SPACE and the address as specifically as you can. E.G. -places Kaivokatu 1, Helsinki, Finland. This ensures that you get as accurate information as possible.",
                        inline=False)
                    await ctx.channel.send(embed=embed)

                else:

                    # Replacing every SPACE string with another string that indicates space. Replace() -function, built-in with Python.
                    address = addressForReplacement.replace(" ", "%20")

                    url = "https://www.mapquestapi.com/geocoding/v1/address?key=" + api_key + \
                        "&inFormat=kvp&outFormat=json&location=" + address + "&thumbMaps=false"

                    # Opening and reading and converting to JSON the coordinates-dict with location attributes.
                    with urllib.request.urlopen(url) as response:
                        html = response.read()
                        # Loads the whole datapoint as JSON.
                        data = json.loads(html)

                    # Setting the desired coordinates from the JSON-output.
                    coordLat = data["results"][0]["locations"][0]["latLng"][
                        "lat"]
                    coordLng = data["results"][0]["locations"][0]["latLng"][
                        "lng"]

                    # Getting the google platform key
                    gmaps = googlemaps.Client(key=GOOGLE_API_KEY)
                    # Google maps own dictionary methods and places find

                    # Using the desired coordinates with gmaps-API. Making int to String conversion for the URL so that it is not N/A.
                    places_result = gmaps.places_nearby(
                        location=str(coordLat) + "," + str(coordLng),
                        radius=1000,
                        open_now=False,
                        type="restaurant")
                    print(places_result)
                    # Bot message awakening and later on adding the address

                    # Opening the list and checking if there are any results - no ERRORS are given when there are no places, THUS creating an informative output.
                    if (len(places_result["results"]) <= 0):

                        embed = discord.Embed(title="Nearby Places",
                                              color=0xf2680c)
                        embed.add_field(
                            name="Error",
                            value=
                            "Could not find any nearby places. Maybe be more specific? Please input the command -places followed by a SPACE and the address as specifically as you can. E.G. -places Kaivokatu 1, Helsinki, Finland. This ensures that you get as accurate information as possible.",
                            inline=False)
                        await ctx.channel.send(embed=embed)

                    else:

                        # Limiting the results to 7 from the desired list...
                        for place in places_result['results'][:5]:
                            # ... These are within 1 km of the desired address. 20 places is the default - too much SPAM on the user's part.

                            # naming place id
                            my_place_id = place['place_id']
                            # naming fields that we want to be seen from the json list
                            my_fields = [
                                'name', 'formatted_address',
                                'formatted_phone_number'
                            ]

                            # goooglemaps' own method for place find with my_fields and place_id
                            place_details = gmaps.place(place_id=my_place_id,
                                                        fields=my_fields)

                            # discords own embed style for clean message
                            embed = discord.Embed(color=0xf2680c,
                                                  title="Places: ")
                            embed.add_field(
                                name="Name: ",
                                value=place_details['result']['name'],
                                inline=True)
                            embed.add_field(name="Address: ",
                                            value=place_details["result"]
                                            ["formatted_address"],
                                            inline=True)

                            # Correcting Keyerrors
                            try:
                                embed.add_field(name="Phone number: ",
                                                value=place_details["result"]
                                                ['formatted_phone_number'],
                                                inline=True)
                            except KeyError:
                                embed.add_field(name="Phone number: ",
                                                value="No number",
                                                inline=True)

                            # Sending places to discord bot
                            await ctx.channel.send(embed=embed)

        except:  # ERROR checking. The last resort. Cacthes anything that went by the above ERROR checks.
            embed = discord.Embed(title="Nearby Places", color=0xf2680c)
            embed.add_field(
                name="Error",
                value=
                "Please input the command -places followed by a SPACE and the address as specifically as you can. E.G. -places Kaivokatu 1, Helsinki, Finland. This ensures that you get as accurate information as possible.",
                inline=False)
Пример #13
0
import googlemaps
import json
import string
import time

gmaps = googlemaps.Client(key='KEY')  #@@@@@@@@REPLACE WITH API KEY!!!!@@@@@
s_num = 1  #step number
origin = None
print(
    "For input below please follow the format: City, State Code /n Example: Boston, MA"
)
if origin == None:
    origin = input("Enter a place of origin:")
    #if ("," not in origin): google client accepts other formats
    #origin = input("Enter a place of origin following format above:")
destination = None
if destination == None:
    destination = input("Please enter the city would you like directions to:")
    #if ("," not in destination): google client accepts other formats
    #origin = input("Where you would like to go? Please follow format above:")
trans_mode = ""
while trans_mode.lower() != "driving" and trans_mode.lower(
) != "bicycling" and trans_mode.lower() != "walking" and trans_mode.lower(
) != "transit":
    print(
        "Please enter ond of the following options below: Driving, Bicycling, Walking, or Transit"
    )
    trans_mode = input("Preferred mode of transprotation from above:").lower()
#goog_directions = "https://maps.googleapis.com/maps/api/directions/json?origin=Boston,+MA&destination=Santa+Carla,+CA&mode=driving&key=AIzaSyAg1ZGxNcWd_pefV6ZG3i_uJ30g-5TTY5c"
#directions from link used for reference to loate items in googlemaps library module
google_directions = gmaps.directions(origin,
Пример #14
0
    with open(csv_name, newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=';')
        i = 0
        for value, row in enumerate(reader, 1):
            if (i != 0):
                address = row[2] + ", " + row[3]
                result = gmaps.geocode(address)
                filewriter.writerow([
                    row[0], result[0]["geometry"]["location"]["lat"],
                    result[0]["geometry"]["location"]["lng"]
                ])
            elif (i == 0):
                i += 1


#_________________________________________________________________________________

gmaps = googlemaps.Client(key='YOUR KEY')
with open('dataset/coordinates.csv', 'w') as csvfile:
    filewriter = csv.writer(csvfile,
                            delimiter=';',
                            quotechar='|',
                            quoting=csv.QUOTE_MINIMAL)
    filewriter.writerow(["URL", "LAT", "LON"])
    hotel_csv = 'dataset/HOTEL BARI E PROVINCIA.csv'
    restaurants_csv = 'dataset/RISTORANTI BARI E PROVINCIA.csv'
    places_csv = 'dataset/LUOGHI D_INTERESSE BARI E PROVINCIA.csv'
    getCoordinates(gmaps, hotel_csv, filewriter)
    getCoordinates(gmaps, restaurants_csv, filewriter)
    getCoordinates(gmaps, places_csv, filewriter)
Пример #15
0
import pandas as pd
import googlemaps
from pprint import pprint
from glmTf import googleUClientCreater

dt_bs = pd.read_csv('data/map_states_in_taipei_copy_NaN.csv')
dt_bs
# dt_bs.to_csv('data/incorrect.csv')
dt_bs[~dt_bs['dist'].isnull()].to_csv("data/map_states_in_taipei_clean_complete.csv")

key = 'AIzaSyDmjTq17LmNHYeoWhf5R57QsxqM92bvaaE'
gms = googlemaps.Client(key=key)

number = 843
dt_bs.iloc[number]['center']

point = (24.985530052272686, 121.61951637420566)
test_res = gms.reverse_geocode(point,language='zh-TW')
pprint(test_res)
political_1 = test_res[0]['address_components'][3]['long_name']
political_2 = test_res[0]['address_components'][2]['long_name']
print(political_1,political_2)

dt_bs.loc[number,'dist'] = '深坑區'
dt_bs.loc[number,'vil'] = '阿柔里'
dt_bs.iloc[number]

# DROP
dt_bs = dt_bs.drop([356],axis=0)

# OUTPUT FILE
Пример #16
0
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 18:25:48 2016

@author: kameelperd64
"""
import googlemaps
gmaps = googlemaps.Client('AIzaSyATRIUPX1HUczj6VZwrEdPmG62ufZG1cpI')


class Node:
    def __init__(self, value, parent, loc, children=[]):
        self.value = value
        self.children = children
        self.parent = parent
        self.loc = loc
        self.shortest = 0


def Build(node, loc=[]):
    node.children = []
    for location in loc:
        node2 = node
        while 1 == 1:
            if node2 == None:
                dist = node.value + getDist(node.loc, location)
                node.children.append(Node(dist, node, location))
                break
            if (node2.loc == location):
                break
            node2 = node2.parent
Пример #17
0
import googlemaps
import csv
from selenium import webdriver
from time import sleep
from urllib.request import urlopen  #for load web page
from bs4 import BeautifulSoup  #for analysis web page

gmaps = googlemaps.Client(key='AIzaSyCvmftDhP4yEN-as8P7pYiT-fwwIjpRhpI')


class MovieTheater:
    def __init__(self):
        f = open('movietheater.csv', 'r')
        csvreader = csv.reader(f)
        self.allData = []
        self.timetable = {}
        for row in csvreader:
            self.allData.append(row)
        f.close()

    def getTheaterInformation(self, theatername):
        ans = {}
        for i in range(len(self.allData)):
            if self.allData[i][0] == theatername:
                ans['addr'] = self.allData[i][1]
                ans['phone'] = self.allData[i][2]
                if i <= 12:
                    ans['url'] = 'https://www.vscinemas.com.tw/'
                elif 12 < i <= 24:
                    ans['url'] = 'http://www.ambassador.com.tw/'
                else:
Пример #18
0
import googlemaps
import sys

gm = googlemaps.Client(key="AIzaSyAdBrRjT1naXA3PbjKcMyZU1WP0SIoFvCU")


def getLocation(address_string):
    coords = gm.geocode(address_string)
    lat = coords[0]['geometry']['location']['lat']
    lon = coords[0]['geometry']['location']['lng']
    return lat, lon


if __name__ == "__main__":
    query = sys.argv[1]
    x = getLocation(query)
    print x
import googlemaps
from googlemaps import places

from tools.json_to_yaml import write_yaml

gmaps = googlemaps.Client(key='AIzaSyCWOSz0D-dfNnfv7FJh6pP3dghHM9NmyuQ')
" https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&keyword=cruise&key=AIzaSyCWOSz0D-dfNnfv7FJh6pP3dghHM9NmyuQ"

# Geocoding an address
geocode_result = places.places_nearby(gmaps,
                                      location='-33.8670522,151.1957362',
                                      radius=1500,
                                      type='restaurant',
                                      keyword='cruise')
write_yaml(geocode_result, 'nearbysearch_result.yaml')
Пример #20
0
 def __init__(self, api_id):
     self.KEY = api_id
     self.gmaps = googlemaps.Client(key=self.KEY)
     self.result = None
 def create_gmaps(self):
     gmaps = googlemaps.Client(key='...')
     # print(gmaps.geocode('서울중부경찰서', language='ko'))
     return gmaps
Пример #22
0
import pandas as pd
import googlemaps
import sys

gcp_key = open('gcp.key', 'r').read()

gmaps = googlemaps.Client(key=gcp_key)

filename = 'l_city_market_id.csv'

df = pd.read_csv('../data/lookups/' + filename)
df = df.sample(n=600)
lookup = {}


def get_gmaps_info(s):
    g = gmaps.geocode(s)[0]['geometry']['location']
    timezone = gmaps.timezone((g['lat'], g['lng']))
    g.update({
        'rawOffset': timezone['rawOffset'],
        'timeZoneName': timezone['timeZoneName']
    })
    return g


i = 0
for index, row in df.iterrows():
    try:
        lookup[int(row['Code'])] = get_gmaps_info(row['Description'])
        i += 1
        print "%d / 600" % i
Пример #23
0
from flask import Flask, render_template, request, jsonify
import requests
import json
from twilio.rest import Client
import googlemaps

account_sid = "AC6b46e74d4a54465a3e4fc824849d121a"
auth_token  = "e4ef218b04c5f93d7eba8b17a94ba1c3"

api_key = "AIzaSyBRl0KG9bvh6DD4kGVoTqM2aRLfjw40VNk"
gmaps = googlemaps.Client(key=api_key)

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('form.html')


@app.route('/process', methods=['POST', 'GET'])
def process():
    if request.method == 'POST':
        email = request.form['email']
        name = request.form['name']
        client = Client(account_sid, auth_token)
        message = client.messages.create(
        to = "+91" + str(email),
        from_="+13346002011",
        body = str(name) + " Ticket has been Booked! QR Code "  )
        data = "OTP has been sent to " + str(email);
    ])
    layout = Layout(
        autosize=True,
        hovermode='closest',
        mapbox=dict(
            accesstoken=mapbox_access_token,
            bearing=0,
            style='streets',
            center=dict(
                lat=np.mean([float(step[0]) for step in steps]),
                lon=np.mean([float(step[1]) for step in steps]),
            ),
            pitch=0,
            zoom=zoom
        ),
    )

    fig = dict(data=data, layout=layout)
    return fig

gmap_api_key = 'AIzaSyCpKt7PVTMeHKPOODBwS3fx3ZJneCNG_w0'

gmaps = googlemaps.Client(gmap_api_key)
address_start = '55 Parsonage Rd.'
address_end = '150th Ave and 147th St'
zoom=12.2
endpt_size=20

fig = plot_route_between_tesla_stations(address_start, address_end, zoom=12.2, endpt_size=20)
py.iplot(fig, filename='tesla-driving-directions-between-superchargers')
Пример #25
0
client = gspread.authorize(creds)

sheet = client.open('Thane_travel_data').sheet1

eef_lat = [
    18.952563, 18.909179, 18.956634, 18.981705, 19.017676, 19.142981, 19.21418,
    19.267896
]
eef_long = [
    72.960334, 72.986411, 73.036789, 73.088119, 73.106271, 73.046689,
    73.012196, 73.080997
]

timestamp = time.strftime('%H:%M')
present_time = time.time()
gmaps = googlemaps.Client(key='AIzaSyBVd5uRVv5gGyvs8Zh9nDWVV96rCVU7LvI')
i = int(sheet.cell(189, 2).value)

for x in range(0, 7):
    origins = (eef_lat[x], eef_long[x])
    destinations = (eef_lat[x + 1], eef_long[x + 1])
    my_distance = gmaps.distance_matrix(origins,
                                        destinations,
                                        departure_time=present_time)
    live_data = my_distance['rows'][0]['elements'][0]['duration_in_traffic'][
        'text']
    sheet.update_cell(i + 2, x + 2, live_data)

sheet.update_cell(i + 2, 1, timestamp)

i = i + 1
Пример #26
0
def lockin():
    if request.method == 'POST':
        # Variable used to search for a manual price
        priceOveride = False
        # Get the form submission method
        submissionMethod = request.form['submit']

        # If we didn't try to confirm a manual price
        if(submissionMethod != "confirm_price"):

            # Get the fuel type we want
            fuelType = str(request.form['fueltype'])
            session['fuelType'] = fuelType

            # Clear previous messages
            session.pop('ErrorMessage', None)
            session.pop('SuccessMessage', None)

            # Get the postcode and price of the cheapest fuel
            locationResult = functions.cheapestFuel(fuelType)

            # They tried to do something different from the manual and automatic form, so throw up an error
            if(submissionMethod != "manual" and submissionMethod != "automatic"):
                session['ErrorMessage'] = "Invalid form submission. Either use the manual or automatic one on the main page."
                return redirect(url_for('index'))

            # If they have manually chosen a postcode/suburb set the price overide to true
            if(submissionMethod == "manual"):
                postcode = str(request.form['postcode'])
                priceOveride = True
                # Get the latitude and longitude from the store
                storeLatLng = functions.getStoreAddress(postcode)
                # If we have a match, set the coordinates. If we don't, use Google Maps
                if (storeLatLng):
                    locLat = float(storeLatLng[0])
                    locLat += (random.uniform(0.01,0.000001) * random.choice([-1,1]))

                    locLong = float(storeLatLng[1])
                    locLong += (random.uniform(0.01,0.000001) * random.choice([-1,1]))
                else:
                    # If we have entered the wrong manual postcode for a store, and haven't
                    # set the Google Maps API, return an error since we cant use the API
                    if not custom_coords:
                        # If it is, get the error message and return back to the index
                        session['ErrorMessage'] = "Error: You entered a manual postcode where no 7-Eleven store is. Please set a Google Maps API key or enter a valid postcode."
                        return redirect(url_for('index'))
                    # Initiate the Google Maps API
                    gmaps = googlemaps.Client(key = API_KEY)
                    # Get the longitude and latitude from the submitted postcode
                    geocode_result = gmaps.geocode(str(request.form['postcode']) + ', Australia')
                    locLat  = geocode_result[0]['geometry']['location']['lat']
                    locLong = geocode_result[0]['geometry']['location']['lng']
            else:
                # It was an automatic submission so we will now get the coordinates of the store
                # and add a random value to it so we don't appear to lock in from the service station
                locLat = locationResult[2]
                locLat += (random.uniform(0.01,0.000001) * random.choice([-1,1]))

                locLong = locationResult[3]
                locLong += (random.uniform(0.01,0.000001) * random.choice([-1,1]))

            # The payload to start the lock in process.
            payload = '{"LastStoreUpdateTimestamp":' + str(int(time.time())) + ',"Latitude":"' + str(locLat) + '","Longitude":"' + str(locLong) + '"}'
            tssa = functions.generateTssa(functions.BASE_URL + "FuelLock/StartSession", "POST", payload, session['accessToken'])

            # Now we start the request header
            headers = {'User-Agent':'Apache-HttpClient/UNAVAILABLE (java 1.4)',
                       'Authorization':'%s' % tssa,
                       'X-OsVersion':functions.OS_VERSION,
                       'X-OsName':'Android',
                       'X-DeviceID':session['DEVICE_ID'],
                       'X-VmobID':functions.des_encrypt_string(session['DEVICE_ID']),
                       'X-AppVersion':functions.APP_VERSION,
                       'X-DeviceSecret':session['deviceSecret'],
                       'Content-Type':'application/json; charset=utf-8'}

            # Send the request
            response = requests.post(functions.BASE_URL + "FuelLock/StartSession", data=payload, headers=headers)

            # Get the response content so we can check the fuel price
            returnContent = response.content

            # Move the response json into an array so we can read it
            returnContent = json.loads(returnContent.decode('utf-8'))

            # If there is a fuel lock already in place we get an error!
            try:
              if returnContent['ErrorType'] == 0:
                  session['ErrorMessage'] = "An error has occured. This is most likely due to a fuel lock already being in place."
                  return redirect(url_for('index'))
            except:
                pass

            # Get the fuel price of all the types of fuel
            for each in returnContent['CheapestFuelTypeStores']:
                x = each['FuelPrices']
                for i in x:
                    if(str(i['Ean']) == fuelType):
                        LockinPrice = i['Price']
                        session['LockinPrice'] = LockinPrice

            # If we have performed an automatic search we run the lowest price check
            # LockinPrice = the price from the 7/11 website
            # locationResult[1] = the price from the master131 script
            # If the price that we tried to lock in is more expensive than scripts price, we return an error
            if not(priceOveride):
                if not(float(LockinPrice) <= float(locationResult[1])):
                    session['ErrorMessage'] = "The fuel price is too high compared to the cheapest available. The cheapest we found was at " + locationResult[0] + ". Try locking in there!"
                    return redirect(url_for('index'))

            if(priceOveride):
                return redirect(url_for('confirm'))

        # Now we want to lock in the maximum litres we can.
        NumberOfLitres = int(float(session['cardBalance']) / session['LockinPrice'] * 100)

        # Lets start the actual lock in process
        payload = '{"AccountId":"' + session['accountID'] + '","FuelType":"' + session['fuelType'] + '","NumberOfLitres":"' + str(NumberOfLitres) + '"}'

        tssa = functions.generateTssa(functions.BASE_URL + "FuelLock/Confirm", "POST", payload, session['accessToken'])

        headers = {'User-Agent':'Apache-HttpClient/UNAVAILABLE (java 1.4)',
                   'Authorization':'%s' % tssa,
                   'X-OsVersion':functions.OS_VERSION,
                   'X-OsName':'Android',
                   'X-DeviceID':session['DEVICE_ID'],
                   'X-VmobID':functions.des_encrypt_string(session['DEVICE_ID']),
                   'X-AppVersion':functions.APP_VERSION,
                   'X-DeviceSecret':session['deviceSecret'],
                   'Content-Type':'application/json; charset=utf-8'}

        # Send through the request and get the response
        response = requests.post(functions.BASE_URL + "FuelLock/Confirm", data=payload, headers=headers)

        # Get the response into a json array
        returnContent = json.loads(response.content.decode('utf-8'))
        try:
            # Check if the response was an error message
            if(returnContent['Message']):
                # If it is, get the error message and return back to the index
                session['ErrorMessage'] = returnContent['Message']
                return redirect(url_for('index'))
            # Otherwise we most likely locked in the price!
            if(returnContent['Status'] == "0"):
                # Update the fuel prices that are locked in
                functions.lockedPrices()
                # Get amoount of litres that was locked in from the returned JSON array
                session['TotalLitres'] = returnContent['TotalLitres']
                session['SuccessMessage'] = "The price was locked in for " + str(session['LockinPrice']) + " cents per litre"

                # Pop our fueltype and lock in price variables
                session.pop('fuelType', None)
                session.pop('LockinPrice', None)
                return redirect(url_for('index'))

        # For whatever reason it saved our lock in anyway and return to the index page
        except:
            # Update the fuel prices that are locked in
            functions.lockedPrices()
            session['SuccessMessage'] = "The price was locked in for " + str(session['LockinPrice']) + " cents per litre"
            # Get amoount of litres that was locked in from the returned JSON array
            session['TotalLitres'] = returnContent['TotalLitres']

            # Pop our fueltype and lock in price variables
            session.pop('fuelType', None)
            session.pop('LockinPrice', None)
            return redirect(url_for('index'))
    else:
        # They just tried to load the lock in page without sending any data
        session['ErrorMessage'] = "Unknown error occured. Please try again!"
        return redirect(url_for('index'))
]  # change here according to your columns in the original file (additional columns)
SHEET_NAME = "Sheet 1"
OUTPUT_NAME = "output_example.xlsx"

if __name__ == "__main__":
    script_name = os.path.relpath(__file__)
    if len(sys.argv) != 2:
        print("Usage: {} <excel file>".format(script_name))
        exit()

    filename = sys.argv[1]
    file = pd.read_excel(filename)
    streets = file['Street']
    numbers = file['House']

    gmaps = googlemaps.Client(key=KEY)
    columns = ['Address', 'x', 'y'] + COLUMNS
    df = dict()
    for col in columns:
        df[col] = []

    for i in tqdm(range(len(file))):
        street = streets[i]
        number = numbers[i]
        address = f"{street} {number}, ירושלים"
        loc = gmaps.geocode(address)
        for l, name in zip(['lng', 'lat'], ['x', 'y']):
            add = loc[0]['geometry']['location'][l]
            df[name].append(add)
        df['Address'].append(address)
        for col in COLUMNS:
# Código desenvolvido para o desafio Nasa Space App pela equipe #430
# Este código solicita sua localização( cidade, país, local específico) e retorna a latitude e longitude

api_key = 'AIzaSyCIUu5YFfu5A_nwFb_E4BkfhqM38OSzOUo'

import pandas as pd
import googlemaps

local_input = input('Digite sua localização (Cidade e Estado):'
                    )  # pode inserir neste local qualquer informação
df = pd.DataFrame(
    {  # sobre o local que deseja, podendo utilizar até código postal                    
        'address': [local_input]
    })

gmaps_key = googlemaps.Client(key='AIzaSyCIUu5YFfu5A_nwFb_E4BkfhqM38OSzOUo')
df['Lat'] = None
df['Lon'] = None
for i in range(len(df)):
    geocode_result = gmaps_key.geocode(df.loc[i, 'address'])
    try:
        lat = geocode_result[0]['geometry']['location']['lat']
        lng = geocode_result[0]['geometry']['location']['lng']
        df.loc[i, 'Lat'] = lat
        df.loc[i, 'Lon'] = lng
    except:
        lat = None
        lng = None
print(df)
Пример #29
0
# !pip3 install -U googlemaps
# https://github.com/chncyhn/simulated-annealing-tsp/blob/master/anneal.py
#

import math
import time
import json
import random
import datetime
from decimal import Decimal

import googlemaps
import collections

# Calling the distance matrix API
gmaps = googlemaps.Client(key='AIzaSyBx0n2ciqzWa6er_BjaDJvXZ6eYr1jKmN0 ')
print("Maximum number of vehicle = 6")
numVehicles = int(input("VEHICLES NUMBERS : "))


def convert(seconds):
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60
    return "%d:%02d:%02d" % (hour, minutes, seconds)


# -------------------------------------------------------------------------------------
################################# SimulatedAnneling ##################################
Пример #30
0
    def test_clientid_not_accepted(self):
        client = googlemaps.Client(client_id="asdf", client_secret="asdf")

        with self.assertRaises(ValueError):
            client.speed_limits("foo")