Example #1
0
def get_lat_long(place):

    search_string = "DisplayPosition"
    lat = 0.0
    long = 0.0
    trig = 0

    try:
        geocoderApi = herepy.GeocoderApi('dy8kVG3quHsuzvzE2IPe',
                                         'krzVA06TkOKIp6Km2Jkdiw')
        response = geocoderApi.free_form(place)

        response = str(response)
        reslen = len(response)

        try:
            for i in range(len(search_string), reslen):
                if response[i - len(search_string):i] == "DisplayPosition":
                    la = response[i + 16:i + 24]
                    lo = response[i + 39:i + 47]
                    lat = float(la)
                    long = float(lo)
                    trig = 1
        except:
            trig = 0
    except:
        trig = -1
    return (trig, lat, long)
Example #2
0
def handler(event, context):
    """
    Handler for the Lambda function.

    Gets the address as input from the AWS AppSync API, then gets the coordinates and other information about the given address using the Geocoder HERE API.
    """

    print('request: {}'.format(json.dumps(event)))
    search_text = event['arguments']['address']

    here_api_key = os.environ['HERE_API_KEY']
    geocoder_api = herepy.GeocoderApi(here_api_key)
    response_here = geocoder_api.free_form(search_text)

    response_location = response_here.items[0]
    response_address = response_location['address']
    response_location = response_location['position']

    address = {
        'street': response_address['label'],
        'city': response_address['city'],
        'state': response_address['state'],
        'country': response_address['countryCode'],
        'latitude': response_location['lat'],
        'longitude': response_location['lng']
    }

    print('response: {}'.format(json.dumps(address)))
    return address
Example #3
0
def get_location_coord(lat, lon, loc, app_id, app_code):
    '''
        Get address and position information by coordinates or location, app_id and app_code are generate when you sing up in here.com in freemium version. 
        If latitude coordinate is null, get information by location data.
    '''

    geocoderApi = herepy.GeocoderApi(app_id, app_code)
    geocoderReverseApi = herepy.GeocoderReverseApi(app_id, app_code)
    address = None
    position = None

    if lat is None or np.isnan(lat):
        response = geocoderApi.free_form(loc)
        if response.as_dict()['Response']['View']:
            address = response.as_dict(
            )['Response']['View'][0]['Result'][0]['Location']['Address']
            position = response.as_dict()['Response']['View'][0]['Result'][0][
                'Location']['DisplayPosition']
    else:
        response = geocoderReverseApi.retrieve_addresses([lat, lon])
        if response.as_dict()['Response']['View']:
            address = response.as_dict(
            )['Response']['View'][0]['Result'][0]['Location']['Address']
            position = response.as_dict()['Response']['View'][0]['Result'][0][
                'Location']['DisplayPosition']
        else:
            response = geocoderApi.free_form(loc)
            if response.as_dict()['Response']['View']:
                address = response.as_dict(
                )['Response']['View'][0]['Result'][0]['Location']['Address']
                position = response.as_dict()['Response']['View'][0]['Result'][
                    0]['Location']['DisplayPosition']

    return address, position
Example #4
0
def geocode(apiID, apiCode, address):
    appID = apiID
    appCode = apiCode

    geocoderApi = herepy.GeocoderApi(appID, appCode)

    geoCodeResponse = geocoderApi.free_form(address)

    data = geoCodeResponse.as_dict()

    lat = data['Response']['View'][0]['Result'][0]['Location'][
        'DisplayPosition']['Latitude']
    lon = data['Response']['View'][0]['Result'][0]['Location'][
        'DisplayPosition']['Longitude']
    relevance = data['Response']['View'][0]['Result'][0]['Relevance']
    matchLevel = data['Response']['View'][0]['Result'][0]['MatchLevel']
    matchQuality = str(
        data['Response']['View'][0]['Result'][0]['MatchQuality'])
    matchType = data['Response']['View'][0]['Result'][0]['MatchType']
    resultAddress = data['Response']['View'][0]['Result'][0]['Location'][
        'Address']['Label']

    print("Latitude: ", lat)
    print("Longitude: ", lon)

    time.sleep(0.1)

    return (lat, lon, relevance, matchLevel, matchQuality, matchType,
            resultAddress)
Example #5
0
def geocoder_here(adress, token=HERE_API_KEY):
    """
    adress: NewYork libery
     ==>  {'lat': 41.79854, 'lng': -74.74493}
    """
    geocoderApi = herepy.GeocoderApi(api_key=token)
    res = geocoderApi.free_form(adress)
    res = res.as_dict()
    coords = res["items"][0]["position"]
    coords = {k.lower(): v for k, v in coords.items()}
    return coords
Example #6
0
 def __init__(self):
     self.modes = {'walk':[herepy.RouteMode.pedestrian,herepy.RouteMode.shortest],'bus':[herepy.RouteMode.publicTransport,herepy.RouteMode.fastest],'car':[herepy.RouteMode.car,herepy.RouteMode.fastest,herepy.RouteMode.traffic_enabled]}
     self.api_key = self.getconfig("maps_api")#"NuWLrM7oE23-PKjQWHD79izu0aFFvYdEu7wZV0SanSE"
     self.max_radius = self.getconfig("maxradius")*1000 #Enter in KM
     self.geocoderApi = herepy.GeocoderApi(self.api_key)
     self.geocoderAutoCompleteApi = herepy.GeocoderAutoCompleteApi(self.api_key)
     self.routingApi = herepy.RoutingApi(self.api_key)
     self.geocoderReverseApi = herepy.GeocoderReverseApi(self.api_key)
     self.placesApi = herepy.PlacesApi(self.api_key)
     self.current_coordinates = [0,0]
     self.loadconfig()
Example #7
0
def geocoder_here(adress, token="hYjanuWQ92oW2KK_Um_1mmNuR7jW14th3hst9jNO_sc"):
    """
    adress: 4 Av du General de Gaulle
     ==>  {'Latitude': 48.85395, 'Longitude': 2.27758}
    """
    geocoderApi = herepy.GeocoderApi(api_key=token)
    res = geocoderApi.free_form(adress)
    res = res.as_dict()
    coords = res["Response"]["View"][0]["Result"][0]["Location"][
        "DisplayPosition"]
    coords = {k.lower(): v for k, v in coords.items()}
    return coords
Example #8
0
    def computeLatLonFromAdress(self, adress):
        """
        TODO
        """
        geocoderApi = herepy.GeocoderApi(self.HERE_ID, self.HERE_PASSWD)

        pos_geocoder = geocoderApi.free_form(adress)
        pos_dict = pos_geocoder.as_dict()['Response']['View'][0]['Result'][0][
            'Location']['NavigationPosition'][0]
        pos = [pos_dict['Latitude'], pos_dict['Longitude']]

        return pos
Example #9
0
def location(place):
    geocoderApi = herepy.GeocoderApi(
        'fywUFbdwhP7YRn5SZI2A-ZJ7te444T2vt3X5GWnveAE')
    response = geocoderApi.free_form(place)
    s = json.loads(str(response))

    lat = s["Response"]["View"][0]["Result"][0]["Location"]["DisplayPosition"][
        "Latitude"]
    lng = s["Response"]["View"][0]["Result"][0]["Location"]["DisplayPosition"][
        "Longitude"]
    lat = "{0:.2f}".format(lat)
    lng = "{0:.2f}".format(lng)
    return '{' + lat + ',' + lng + '}'
Example #10
0
    def getForecaster(self, location):
        # Get coordinates from address.
        geocoderApi = herepy.GeocoderApi(Extension.herepy_appId,
                                         Extension.herepy_appCode)
        jsonResponse = geocoderApi.free_form(' '.join(location))
        coords = jsonResponse.as_dict()['Response']['View'][0]['Result'][0][
            'Location']['NavigationPosition'][0]

        # Making ForecastIO object from coordinates.
        return ForecastIO.ForecastIO(Extension.dsw_apiKey,
                                     units=ForecastIO.ForecastIO.UNITS_SI,
                                     lang=ForecastIO.ForecastIO.LANG_ENGLISH,
                                     latitude=coords['Latitude'],
                                     longitude=coords['Longitude'])
Example #11
0
def geocoder_here(adress, token=HERE_API_KEY):
    """
    adress: 4 Av du General de Gaulle
     ==>  {'Latitude': 48.85395, 'Longitude': 2.27758}
    """
    geocoderApi = herepy.GeocoderApi(api_key=token)
    res = geocoderApi.free_form(adress)
    res = res.as_dict()
    coords = coords = res['items'][0]['position']
    coords = {k.lower(): v for k, v in coords.items()}
    #j'ai rajouté cette ligne

    coords = dict(lat=coords['lat'], lon=coords['lng'])

    return coords
Example #12
0
def get_phone_number():
    loc = worker()
    geocoderApi = herepy.GeocoderApi('rTc2ExgvmtXRk5fJG3IB', 'HwAH1Q70PPoaHB-hqswuHQ')
    geocoderReverseApi = herepy.GeocoderReverseApi('rTc2ExgvmtXRk5fJG3IB', 'HwAH1Q70PPoaHB-hqswuHQ')
    response = requests.get('https://places.cit.api.here.com/places/v1/autosuggest?at=37.787541999999995,-122.4109585&q=police&station&app_id=rTc2ExgvmtXRk5fJG3IB&app_code=HwAH1Q70PPoaHB-hqswuHQ')

    parsed = json.loads(response.text)

    url = parsed['results'][0]['href']
    response2 = requests.get(url)
    parsed2 = json.loads(response2.text)
    station_url = parsed2['results']['items'][0]['href']

    response3 = requests.get(station_url)
    parsed3 = json.loads(response3.text)
    phoneNumber = parsed3['contacts']['phone'][0]['value']
    print(phoneNumber)
Example #13
0
## importing the necessary files

from ast import literal_eval
from credentials import APP_ID, APP_CODE
import herepy
import json
from read import point1, point2

## setting up credentials and calling the api's

routingApi = herepy.RoutingApi(APP_ID, APP_CODE)
geocoderapi = herepy.GeocoderApi(APP_ID, APP_CODE)

## taking input of the area we want to start our journey

response1 = geocoderapi.free_form(
    'E-orbit cinema sai nagar amravati maharashtra')
response1.as_json_string()
f = open('result.json', 'w')
f.write(str(response1))
f.close()
a, b = point1()

## taking the input of the area we want to go

response2 = geocoderapi.free_form(
    "Brijlal Biyani Science college Ravi nagar Amravati Maharashtra")
response2.as_json_string()
f = open('result2.json', 'w')
f.write(str(response2))
f.close()
Example #14
0
 def setUp(self):
     api = herepy.GeocoderApi('app_id', 'app_code')
     self._api = api
#####

if __name__=='__main__':

    #Getting the API config
    with open("config.yml", 'r') as stream:
        try:
            cfg = yaml.safe_load(stream)
        except yaml.YAMLError as exc:
            print(exc)

    HERE_ID = cfg["here_api"]["here_id"]
    HERE_PASSWD = cfg["here_api"]["here_passwd"]

    geocoderApi = herepy.GeocoderApi(HERE_ID, HERE_PASSWD)
    routingPublicTransportApi = herepy.public_transit_api.PublicTransitApi(HERE_ID, HERE_PASSWD)
    routingApi = herepy.routing_api.RoutingApi(HERE_ID, HERE_PASSWD)
    placesApi = herepy.places_api.PlacesApi(HERE_ID, HERE_PASSWD)

    #####

    start_pos_geocoder = geocoderApi.free_form('44 Tehama San Francisco CA')  #object of type GeocoderResponse
    # start_pos_geocoder = geocoderApi.free_form('298 W McKinley Sunnyvale CA')
    end_pos_geocoder = geocoderApi.free_form('111 Charles Sunnyvale CA')
    start_pos_dict = start_pos_geocoder.as_dict()['Response']['View'][0]['Result'][0]['Location']['NavigationPosition'][0]
    end_pos_dict = end_pos_geocoder.as_dict()['Response']['View'][0]['Result'][0]['Location']['NavigationPosition'][0]

    # #####
    #
    start_pos = [start_pos_dict['Latitude'], start_pos_dict['Longitude']]
Example #16
0
# coding: utf-8

# In[6]:

# In[67]:

import herepy

# In[68]:

geocoderApi = herepy.GeocoderApi('ZScu1x4Vpek7ifBeLhbq',
                                 'WnXYEtv1dTUluyEiXpnK4A')
response = geocoderApi.free_form('Dmitrovskoye Shosse, 9, Moscow, Russia')
routingApi = herepy.RoutingApi('ZScu1x4Vpek7ifBeLhbq',
                               'WnXYEtv1dTUluyEiXpnK4A')

# In[70]:

#print(response)
latitude = response.Response['View'][0]['Result'][0]['Location'][
    'DisplayPosition']['Latitude']
longitude = response.Response['View'][0]['Result'][0]['Location'][
    'DisplayPosition']['Longitude']

#distance to india

routingApi = herepy.RoutingApi('ZScu1x4Vpek7ifBeLhbq',
                               'WnXYEtv1dTUluyEiXpnK4A')
response = routingApi.car_route(
    [19.174, 72.86], [latitude, longitude],
    [herepy.RouteMode.car, herepy.RouteMode.fastest])
Example #17
0
                namedEntity = json.loads(line)
                queryDb = db_query.queryDatabase(namedEntity)

        except (Exception) as error:
            print("Datenbankabfrage konnte nicht durchgefuehrt werden: ",
                  error)

        finally:
            if (connectionDB):
                cursor.close()
                connectionDB.close()

        # Query spaCy for locations
        try:
            fileCoordinates = open("coordinates.txt", "w")
            geocoderApi = herepy.GeocoderApi(authentification.appID,
                                             authentification.appCode)

            #Combine named Entities
            locations = []
            combinations = []
            numLine = 0
            tweet = ""
            for line in lines:
                namedEntity = json.loads(line)
                if (numLine == 0):
                    locations.append(namedEntity["location"])
                    tweet = namedEntity["text"]
                elif ((tweet == namedEntity["text"]) == True):
                    locations.append(namedEntity["location"])
                else:
                    tweet = loc_combination.combine_locations(
Example #18
0
 def setUp(self):
     api = herepy.GeocoderApi("api_key")
     self._api = api
Example #19
0
script_path = os.path.abspath('__file__')
path_list = script_path.split(os.sep)
script_directory = path_list[0:len(path_list) - 1]
rel_path = "/PL_GLP_GNC_colonia.xlsx"
path = "/".join(script_directory) + "/" + rel_path

# In[136]:

###Read excel file
df = pd.read_excel(path)
print(df[:3])

# In[137]:

###Insert the API and test the code with one record and test the API
geocoderApi = herepy.GeocoderApi('XXXXXXXXXXXX', 'XXXXXXXXXXXX')
response = HEREModel.as_dict(
    geocoderApi.free_form('200 S Mathilda Sunnyvale CA'))
print(response)
type(response)

# In[139]:

### Test Subset of data from dictionary
df1 = [
    response['Response']['View'][0]['Result'][0]['Relevance'],
    response['Response']['View'][0]['Result'][0]['Location']['DisplayPosition']
    ['Latitude'], response['Response']['View'][0]['Result'][0]['Location']
    ['DisplayPosition']['Longitude']
]
print(df1)
Example #20
0
#   This Script gets a CSV file as input with the next format:
#       |   Location    |   GeoLocation         |
#       |   Name        |   longitude, latitude   |
#   It returns a CSV file with the GeoLocation field filled out, when possible
import herepy
import json
import csv

geocoderApi = herepy.GeocoderApi('YOUR_API_KEY')

r = csv.reader(open('locationsFile.csv', 'r', encoding='utf-8', newline=''),
               delimiter='\t')
lines = list(r)

#Location   ->  Column 0
#Geolocation    ->  Column 1
count = 0
for i in range(lines - 1):
    if i == 0:
        continue
    location = lines[i][0]
    geoLocation = lines[i][1]
    #print("Location", location)
    #print("GeoLocation", geoLocation)
    if i % 5000 == 0:
        print(i)
    #If there is already geolocation, get to next entry
    if geoLocation != 'None' and geoLocation != '':
        print("coordenadas", geoLocation)
        continue
    #If there is no location to translate into coordinates, get to next entry
Example #21
0
#!/usr/bin/env python
# coding: utf-8

# In[5]:


import herepy
import json
import requests

geocoderApi = herepy.GeocoderApi('rTc2ExgvmtXRk5fJG3IB', 'HwAH1Q70PPoaHB-hqswuHQ')
geocoderReverseApi = herepy.GeocoderReverseApi('rTc2ExgvmtXRk5fJG3IB', 'HwAH1Q70PPoaHB-hqswuHQ')

from locations import location_data

loc = location_data()


# In[6]:



response = requests.get('https://places.cit.api.here.com/places/v1/autosuggest?at='+loc+'&q=police&station&app_id=rTc2ExgvmtXRk5fJG3IB&app_code=HwAH1Q70PPoaHB-hqswuHQ')

parsed = json.loads(response.text)

url = parsed['results'][0]['href']
response2 = requests.get(url)
parsed2 = json.loads(response2.text)
station_url = parsed2['results']['items'][0]['href']
Example #22
0
 def setUp(self):
     api = herepy.GeocoderApi('api_key')
     self._api = api
def calculoDistancias(endereco1, endereco2):

    routingApi = herepy.RoutingApi('o6i9v6u7AQdyeVTbJwWw',
                                   'kp3lhUcL0KmT-gODan27iw')

    geocoderApi = herepy.GeocoderApi('o6i9v6u7AQdyeVTbJwWw',
                                     'kp3lhUcL0KmT-gODan27iw')

    #response2 = routingApi.truck_route([11.0, 12.0], [22.0, 23.0], [herepy.RouteMode.truck, herepy.RouteMode.fastest])

    #####      Endereco 1     #####

    localizacaoCompleta = geocoderApi.free_form(endereco1)
    data = json.loads(str(localizacaoCompleta))

    pontoLatitude = data['Response']['View'][0]['Result'][0]['Location'][
        'DisplayPosition']['Latitude']
    #print("pontoLatitude:", pontoLatitude)

    pontoLongitude = data['Response']['View'][0]['Result'][0]['Location'][
        'DisplayPosition']['Longitude']
    #print("pontoLongitude:", pontoLongitude)

    posicaoEndereco1 = []

    posicaoEndereco1.append(float(pontoLatitude))
    posicaoEndereco1.append(float(pontoLongitude))

    #Imprimir JSON
    #print(json.dumps(data, indent=4, sort_keys=True))
    #response = geocoderApi.street_intersection('Joao Bento Silvares Sao Mateus Espirito Santo Brasil', 'Nelson Fundao Sao Mateus Espirito Santo Brasil')

    #####      Endereco 2     #####

    localizacaoCompleta = geocoderApi.free_form(endereco2)
    data = json.loads(str(localizacaoCompleta))

    pontoLatitude = data['Response']['View'][0]['Result'][0]['Location'][
        'DisplayPosition']['Latitude']
    #print("pontoLatitude:", pontoLatitude)

    pontoLongitude = data['Response']['View'][0]['Result'][0]['Location'][
        'DisplayPosition']['Longitude']
    #print("pontoLongitude:", pontoLongitude)

    posicaoEndereco2 = []

    posicaoEndereco2.append(float(pontoLatitude))
    posicaoEndereco2.append(float(pontoLongitude))

    #####      Calcula distancia entre os dois enderecos     #####
    response = routingApi.truck_route(
        posicaoEndereco1, posicaoEndereco2,
        [herepy.RouteMode.car, herepy.RouteMode.fastest])
    #print (response)

    data = json.loads(str(response))
    #print(json.dumps(data, indent=4, sort_keys=True))

    print(endereco1 + " - " + endereco2)
    print("Distancia em metros")
    print(data['response']['route'][0]['summary']['distance'])
    print("Tempo em segundos")
    print(data['response']['route'][0]['summary']['travelTime'])

    #retorna a distancia e o tempo
    return data['response']['route'][0]['summary']['distance'], data[
        'response']['route'][0]['summary']['travelTime']
    <textarea id="element_2" name="element_2" class="element textarea medium"></textarea> 
</div>
</li>
</ul>
<p>
<button type="button" onclick="alert('You submitted!')">Submit!</button>
</p>"""

m = folium.Map(location=[45.372, -121.6972], zoom_start=12, tiles='Stamen Terrain')


app_id = 'kj5O3uIQcg0mzyy6Dyeb'

app_code = 'UYxM0q2BZXVoHqthopku6A'

geocoderApi = herepy.GeocoderApi(app_id, app_code)

placesApi = herepy.PlacesApi(app_id, app_code)

# response = placesApi.onebox_search([-25.2744,133.7751], 'pool')

m = folium.Map(location=[-25.2744,133.7751],
                zoom_start=4,
                tiles='Stamen Terrain')

def generate_layer(search_text,coords,colour):
    response = placesApi.onebox_search(coords, search_text)

    df = json_normalize(response.results,'items')

    layer = folium.FeatureGroup(name=search_text)
Example #25
0
def makeWebhookResult(req):
    if req.get("queryResult").get("action") == "symptom":
        result = req.get("queryResult")
        parameters = result.get("parameters")
        symptom = parameters.get("symptom")
        disease = diseaseprediction.dosomething(symptom)
        print(disease)
        #speech = "you may have " + disease + ". Please, consult your doctor."
        #print(speech)
        if not disease:
            speech = "For further details Please click on the below link"
            disease = symptom[0]
        else:
            speech = "you may have " + disease + ". Please, consult your doctor."

        return {
            "fulfillmentText":
            speech,
            "fulfillmentMessages": [{
                "platform": "ACTIONS_ON_GOOGLE",
                "simpleResponses": {
                    "simpleResponses": [{
                        "textToSpeech": speech
                    }]
                }
            }, {
                "platform": "ACTIONS_ON_GOOGLE",
                "linkOutSuggestion": {
                    "destinationName":
                    "Details of disease",
                    "uri":
                    "https://www.webmd.com/search/search_results/default.aspx?query="
                    + disease
                }
            }, {
                "platform": "ACTIONS_ON_GOOGLE",
                "suggestions": {
                    "suggestions": [{
                        "title": "Predict disease"
                    }, {
                        "title": "Details about disease"
                    }, {
                        "title": "Know nearby hospitals"
                    }, {
                        "title": "Thank you"
                    }]
                }
            }]
        }
    if req.get("queryResult").get(
            "action") == "Detailsaboutsymptoms.Detailsaboutsymptoms-custom":
        result = req.get("queryResult")
        parameters = result.get("parameters")
        symptom = parameters.get("disease")
        speech = "For further details Please click on the below link"
        disease = symptom
        return {
            "fulfillmentText":
            speech,
            "fulfillmentMessages": [{
                "platform": "ACTIONS_ON_GOOGLE",
                "simpleResponses": {
                    "simpleResponses": [{
                        "textToSpeech": speech
                    }]
                }
            }, {
                "platform": "ACTIONS_ON_GOOGLE",
                "linkOutSuggestion": {
                    "destinationName":
                    "Details of disease",
                    "uri":
                    "https://www.webmd.com/search/search_results/default.aspx?query="
                    + disease
                }
            }, {
                "platform": "ACTIONS_ON_GOOGLE",
                "suggestions": {
                    "suggestions": [{
                        "title": "Predict disease"
                    }, {
                        "title": "Details about disease"
                    }, {
                        "title": "Know nearby hospitals"
                    }, {
                        "title": "Thank you"
                    }]
                }
            }]
        }
    if req.get("queryResult").get("action") == "google":
        result = req.get("queryResult")
        parameters = result.get("parameters")
        location = parameters.get("geo-city")
        hospital_name = []
        hospital_address = []
        speech = ""
        geocoderApi = herepy.GeocoderApi(
            'NYzvNeZQL5quJfEWEUccVGR-nXIIVt3PeFj1X11dWkw')
        placesApi = herepy.PlacesApi(
            'NYzvNeZQL5quJfEWEUccVGR-nXIIVt3PeFj1X11dWkw')

        response = geocoderApi.free_form(location)
        dict = response.as_dict()
        print(dict)
        position = dict['items'][0]['position']
        latitude = position['lat']
        longitude = position['lng']

        response = placesApi.category_places_at(
            [latitude, longitude],
            [herepy.PlacesCategory.hospital_health_care_facility])
        dict = response.as_dict()

        for i in range(0, 10):
            #print(places_result["results"])
            hospitalname = dict["results"]["items"][i]["title"]
            hospital_name.append(hospitalname)

            hospitaladdress = dict["results"]["items"][i]["vicinity"]
            hospital_address.append(hospitaladdress)

        for i in range(0, len(hospital_name)):
            speech += "<br/><br/>Hospital name: " + hospital_name[
                i] + "<br/>Hospital Address: " + hospital_address[i]
        return {
            "fulfillmentText":
            speech,
            "fulfillmentMessages": [{
                "platform": "ACTIONS_ON_GOOGLE",
                "simpleResponses": {
                    "simpleResponses": [{
                        "textToSpeech": speech
                    }]
                }
            }, {
                "platform": "ACTIONS_ON_GOOGLE",
                "suggestions": {
                    "suggestions": [{
                        "title": "Predict disease"
                    }, {
                        "title": "Details about disease"
                    }, {
                        "title": "Know nearby hospitals"
                    }, {
                        "title": "Thank you"
                    }]
                }
            }]
        }
Example #26
0
from flask import Flask, render_template, request

import json
import herepy
import plotly
import datetime
import dateutil.parser

import pandas as pd
import numpy as np

# initial geocoder and read in NYTimes data
geocoderApi = herepy.GeocoderApi('VbY-MyI6ZT9U8h-Y5GP5W1YaOzQuvNnL4aSTulNEyEQ')


def lat_lon_of_address(addr):
    response = geocoderApi.free_form(addr)
    type(response)
    result = response.as_json_string()
    res = eval(result)
    (lat, lon) = (res['Response']['View'][0]['Result'][0]['Location']
                  ['DisplayPosition']['Latitude'], res['Response']['View'][0]
                  ['Result'][0]['Location']['DisplayPosition']['Longitude'])
    return (lat, lon)


def county_state_of_address(addr):
    response = geocoderApi.free_form(addr)
    type(response)
    result = response.as_json_string()
    res = eval(result)
Example #27
0
# coding: utf-8

# In[1]:

import herepy
import io
import shutil
import os
import sys
import re

# https://www.shanelynn.ie/batch-geocoding-in-python-with-google-geocoding-api/

# In[2]:

geocoderApi = herepy.GeocoderApi('api-key')

# In[21]:

get_ipython().run_line_magic('time', '')

parse_file = open('parse_result_2.csv', "r", encoding='utf-8')
paragraphs = []
ptext = ''
precinct_place_flag = 0
curr_precinct_place = ''
curr_precinct_place_lat = ''
curr_precinct_place_lon = ''
curr_precinct_number = ''
paragraphs.append('precinct_number,precinct_place,p_lat,p_lon,address,lat,lon')
Example #28
0
import configparser
import herepy
import json
import datetime

#CONS
MARGIN = 300

# API key (in config.ini)
config = configparser.ConfigParser()
config.read('config.ini')
api_key = config['HERE']['key']

#API's
geocoderApi = herepy.GeocoderApi(api_key)
routingApi = herepy.RoutingApi(api_key)


def address_to_geo(address):
    response = geocoderApi.free_form(address)
    data = json.loads(response.as_json_string())
    lat = data['items'][0]['access'][0]['lat']
    long = data['items'][0]['access'][0]['lng']
    return [lat, long]


def get_traveltime(start_address, end_address):
    start = address_to_geo(start_address)
    end = address_to_geo(end_address)
    response = routingApi.pedastrian_route(start,
                                           end,