Esempio n. 1
0
def extract_route(lat1, long1, lat2, long2):
    routingApi = herepy.RoutingApi('dpwPxdRJaF8n59ULKx8R',
                                   'ldLYs1bJmd-MguUYeSiL6w')
    response = routingApi.car_route(
        [lat1, long1], [lat2, long2],
        [herepy.RouteMode.car, herepy.RouteMode.fastest])
    return response
Esempio n. 2
0
 def test_carroute_when_error_invalid_credentials_occured(self):
     with open('testdata/models/routing_error_invalid_credentials.json', 'r') as f:
         expectedResponse = f.read()
     responses.add(responses.GET, 'https://route.ls.hereapi.com/routing/7.2/calculateroute.json',
               expectedResponse, status=200)
     api = herepy.RoutingApi('wrong_api_key', 'wrong_app_code')
     with self.assertRaises(herepy.InvalidCredentialsError):
         api.car_route([11.0, 12.0], [22.0, 23.0])
Esempio n. 3
0
async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the HERE travel time platform."""
    api_key = config[CONF_API_KEY]
    here_client = herepy.RoutingApi(api_key)

    if not await hass.async_add_executor_job(_are_valid_client_credentials,
                                             here_client):
        _LOGGER.error(
            "Invalid credentials. This error is returned if the specified token was invalid or no contract could be found for this token"
        )
        return

    if config.get(CONF_ORIGIN_LATITUDE) is not None:
        origin = f"{config[CONF_ORIGIN_LATITUDE]},{config[CONF_ORIGIN_LONGITUDE]}"
        origin_entity_id = None
    else:
        origin = None
        origin_entity_id = config[CONF_ORIGIN_ENTITY_ID]

    if config.get(CONF_DESTINATION_LATITUDE) is not None:
        destination = (
            f"{config[CONF_DESTINATION_LATITUDE]},{config[CONF_DESTINATION_LONGITUDE]}"
        )
        destination_entity_id = None
    else:
        destination = None
        destination_entity_id = config[CONF_DESTINATION_ENTITY_ID]

    traffic_mode = config[CONF_TRAFFIC_MODE]
    name = config[CONF_NAME]

    here_travel_time_config = HERETravelTimeConfig(
        origin=origin,
        destination=destination,
        origin_entity_id=origin_entity_id,
        destination_entity_id=destination_entity_id,
        travel_mode=config[CONF_MODE],
        route_mode=config[CONF_ROUTE_MODE],
        units=config.get(CONF_UNIT_SYSTEM, hass.config.units.name),
        arrival=config.get(CONF_ARRIVAL),
        departure=config.get(CONF_DEPARTURE),
    )

    coordinator = HereTravelTimeDataUpdateCoordinator(
        hass,
        here_client,
        here_travel_time_config,
    )
    await coordinator.async_config_entry_first_refresh()

    sensor = HERETravelTimeSensor(name, traffic_mode, coordinator)

    async_add_entities([sensor])
Esempio n. 4
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()
Esempio n. 5
0
 def test_truckroute_when_error_invalid_credentials_occured(self):
     with open("testdata/models/routing_error_invalid_credentials.json", "r") as f:
         expectedResponse = f.read()
     responses.add(
         responses.GET,
         "https://route.ls.hereapi.com/routing/7.2/calculateroute.json",
         expectedResponse,
         status=200,
     )
     api = herepy.RoutingApi("wrong_api_key", "wrong_app_code")
     with self.assertRaises(herepy.InvalidCredentialsError):
         api.truck_route([11.0, 12.0], [22.0, 23.0])
Esempio n. 6
0
 def test_publictransport_when_error_invalid_credentials_occured(self):
     with open('testdata/models/routing_error_invalid_credentials.json',
               'r') as f:
         expectedResponse = f.read()
     responses.add(
         responses.GET,
         'https://route.cit.api.here.com/routing/7.2/calculateroute.json',
         expectedResponse,
         status=200)
     api = herepy.RoutingApi('wrong_app_id', 'wrong_app_code')
     with self.assertRaises(herepy.InvalidCredentialsError):
         api.public_transport([11.0, 12.0], [15.0, 16.0], True)
Esempio n. 7
0
async def async_setup_platform(
    hass: HomeAssistant,
    config: Dict[str, Union[str, bool]],
    async_add_entities: Callable,
    discovery_info: Optional[DiscoveryInfoType] = None,
) -> None:
    """Set up the HERE travel time platform."""

    api_key = config[CONF_API_KEY]
    here_client = herepy.RoutingApi(api_key)

    if not await hass.async_add_executor_job(
        _are_valid_client_credentials, here_client
    ):
        _LOGGER.error(
            "Invalid credentials. This error is returned if the specified token was invalid or no contract could be found for this token."
        )
        return

    if config.get(CONF_ORIGIN_LATITUDE) is not None:
        origin = f"{config[CONF_ORIGIN_LATITUDE]},{config[CONF_ORIGIN_LONGITUDE]}"
        origin_entity_id = None
    else:
        origin = None
        origin_entity_id = config[CONF_ORIGIN_ENTITY_ID]

    if config.get(CONF_DESTINATION_LATITUDE) is not None:
        destination = (
            f"{config[CONF_DESTINATION_LATITUDE]},{config[CONF_DESTINATION_LONGITUDE]}"
        )
        destination_entity_id = None
    else:
        destination = None
        destination_entity_id = config[CONF_DESTINATION_ENTITY_ID]

    travel_mode = config[CONF_MODE]
    traffic_mode = config[CONF_TRAFFIC_MODE]
    route_mode = config[CONF_ROUTE_MODE]
    name = config[CONF_NAME]
    units = config.get(CONF_UNIT_SYSTEM, hass.config.units.name)
    arrival = config.get(CONF_ARRIVAL)
    departure = config.get(CONF_DEPARTURE)

    here_data = HERETravelTimeData(
        here_client, travel_mode, traffic_mode, route_mode, units, arrival, departure
    )

    sensor = HERETravelTimeSensor(
        name, origin, destination, origin_entity_id, destination_entity_id, here_data
    )

    async_add_entities([sensor])
Esempio n. 8
0
def carRouting(apiID, apiCode, orig, dest):
    appID = apiID
    appCode = apiCode

    routingApi = herepy.RoutingApi(appID, appCode)

    lat, lng = map(float, orig.strip('()').split(','))
    lat2, lng2 = map(float, dest.strip('()').split(','))

    getRoutingData = routingApi.car_route(
        [lat, lng], [lat2, lng2],
        [herepy.RouteMode.car, herepy.RouteMode.fastest])

    #print(getRoutingData)
    try:

        RoutingData = getRoutingData.as_dict()

        OriginLat = RoutingData['response']['route'][0]['waypoint'][0][
            'originalPosition']['latitude']
        Originlon = RoutingData['response']['route'][0]['waypoint'][0][
            'originalPosition']['longitude']
        DestLat = RoutingData['response']['route'][0]['waypoint'][0][
            'mappedPosition']['latitude']
        Destlon = RoutingData['response']['route'][0]['waypoint'][0][
            'mappedPosition']['longitude']
        traffictime = RoutingData['response']['route'][0]['summary'][
            'trafficTime']
        traffictime = int(traffictime) / 60
        basetime = RoutingData['response']['route'][0]['summary']['baseTime']
        text = RoutingData['response']['route'][0]['summary']['text']
        text = text.replace("""<span class="length">""",
                            "").replace("</span>",
                                        "").replace("""<span class="time">""",
                                                    "")
        time.sleep(0.1)

        return (OriginLat, Originlon, DestLat, Destlon, traffictime, basetime,
                text)

    except:

        OriginLat = np.nan
        Originlon = np.nan
        DestLat = np.nan
        Destlon = np.nan
        traffictime = np.nan
        basetime = np.nan
        text = np.nan
        return (OriginLat, Originlon, DestLat, Destlon, traffictime, basetime,
                text)
Esempio n. 9
0
def publicRouting(apiID, apiCode, orig, dest):
    appID = apiID
    appCode = apiCode

    ProutingApi = herepy.RoutingApi(appID, appCode)

    lat, lng = map(float, orig.strip('()').split(','))
    lat2, lng2 = map(float, dest.strip('()').split(','))

    getPRoutingData = ProutingApi.public_transport(
        [lat, lng], [lat2, lng2], True,
        [herepy.RouteMode.publicTransport, herepy.RouteMode.fastest])

    try:

        PublicRoutingData = getPRoutingData.as_dict()

        OriginLat = PublicRoutingData['response']['route'][0]['waypoint'][0][
            'originalPosition']['latitude']
        Originlon = PublicRoutingData['response']['route'][0]['waypoint'][0][
            'originalPosition']['longitude']
        DestLat = PublicRoutingData['response']['route'][0]['waypoint'][0][
            'mappedPosition']['latitude']
        Destlon = PublicRoutingData['response']['route'][0]['waypoint'][0][
            'mappedPosition']['longitude']
        basetime = PublicRoutingData['response']['route'][0]['summary'][
            'baseTime']
        basetime = int(basetime) / 60
        text = PublicRoutingData['response']['route'][0]['summary']['text']
        text = text.replace("""<span class="length">""",
                            "").replace("</span>",
                                        "").replace("""<span class="time">""",
                                                    "")

        time.sleep(0.1)

        return (OriginLat, Originlon, DestLat, Destlon, basetime, text)

    except:
        OriginLat = np.nan
        Originlon = np.nan
        DestLat = np.nan
        Destlon = np.nan
        basetime = np.nan
        text = np.nan
        return (OriginLat, Originlon, DestLat, Destlon, basetime, text)
Esempio n. 10
0
 def __init__(self, origin, destination, app_id, app_code, travel_mode,
              traffic_mode, route_mode, units):
     """Initialize herepy."""
     self.origin = origin
     self.destination = destination
     self.travel_mode = travel_mode
     self.traffic_mode = traffic_mode
     self.route_mode = route_mode
     self.attribution = None
     self.duration = None
     self.distance = None
     self.route = None
     self.base_time = None
     self.origin_name = None
     self.destination_name = None
     self.units = units
     self._client = herepy.RoutingApi(app_id, app_code)
Esempio n. 11
0
def calcDeliveryTime(ori, dest):
    start_time = time.time()

    routingApi = herepy.RoutingApi(os.getenv("HERE_KEY"))

    response = routingApi.truck_route([ori.get('latitude'), ori.get('longitude')], [dest.get('latitude'), dest.get('longitude')], [herepy.RouteMode.truck, herepy.RouteMode.fastest]).as_dict()
    distance = response.get('response').get('route')[0].get('summary').get('distance') / 1000

    if distance < 51:
        deltime = 6
    elif distance > 50 and distance < 701:
        deltime = 24
    elif distance > 700 and distance < 1400:
        deltime = 48
    else:
        deltime = 72

    print(deltime)
    print('--- Tiempo de ejecucion calcDeliveryTime: {} segundos ---'.format((time.time() - start_time)))

    return deltime, distance
Esempio n. 12
0
    def getDeliveryTime(ori, dest):

        """ Get routing time based on coordinates for origin and destination using HERE routing API.

        Returns:
            string: Returns delivery time and distance calculated with Here API.
        """

        start_time = time.time()

        routingApi = herepy.RoutingApi(os.getenv("HERE_KEY"))
        gm = GoogleMaps(os.getenv("GOOGLE_KEY"))

        try:
            response = routingApi.truck_route(ori.coords[::-1], dest.coords[::-1], [herepy.RouteMode.truck, herepy.RouteMode.fastest]).as_dict()
            distance = response.get('response').get('route')[0].get('summary').get('distance') / 1000
        except herepy.error.HEREError:
            try:
                response = gm.distance_matrix(ori.coords[::-1], dest.coords[::-1], mode="driving", departure_time=dt.datetime.now(), traffic_model="pessimistic")
                distance = response.get('rows')[0].get('elements')[0].get('distance').get('value') / 1000
            except Exception as e:
                capture_exception(e)
                raise e

        if distance < 51:
            deltime = 6
        elif distance > 50 and distance < 701:
            deltime = 24
        elif distance > 700 and distance < 1400:
            deltime = 48
        else:
            deltime = 72

        print('--- Tiempo de ejecucion calcDeliveryTime: {} segundos ---'.format((time.time() - start_time)))

        return deltime, distance
Esempio n. 13
0
 def __init__(self, app_id, app_code):
     super(LocationManager, self).__init__()
     self.geo = herepy.geocoder_api.GeocoderApi(app_id=app_id,
                                                app_code=app_code)
     self.rout = herepy.RoutingApi(app_id=app_id, app_code=app_code)
Esempio n. 14
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])
Esempio n. 15
0
 def setUp(self):
     api = herepy.RoutingApi('api_key')
     self._api = api
Esempio n. 16
0
 def setUp(self):
     api = herepy.RoutingApi("api_key")
     self._api = api
Esempio n. 17
0
    def totalRouting_dataset(fpath, column_name1, column_name2):
        try:
            data = pd.read_excel(fpath)

        except:

            try:
                data = pd.read_csv(fpath)

            except:
                "Input File Read Error!! Please check Format."

        for i in range(len(data)):

            for t in range(00, 24):
                try:
                    title = 'Car' + str(t)

                    if t < 10:
                        hour = t
                        flag = 1
                    if t >= 10 and t < 24:
                        hour = t
                        flag = 0
                    if t == 24:
                        hour = 00
                        flag = 0
                    #print(hour)
                    routingApi = herepy.RoutingApi(appID, appCode)
                    ProutingApi = herepy.RoutingApi(appID, appCode)

                    location1 = data.loc[i, column_name1]
                    location2 = data.loc[i, column_name2]

                    lat, lng = map(float, location1.strip('()').split(','))
                    lat2, lng2 = map(float, location2.strip('()').split(','))

                    if flag == 1:
                        getRoutingData = routingApi.car_route(
                            [lat, lng], [lat2, lng2],
                            '2018-10-10T0' + str(hour) + ':00:00',
                            [herepy.RouteMode.car, herepy.RouteMode.fastest])
                    if flag == 0:
                        getRoutingData = routingApi.car_route(
                            [lat, lng], [lat2, lng2],
                            '2018-10-10T' + str(hour) + ':00:00',
                            [herepy.RouteMode.car, herepy.RouteMode.fastest])

                    RoutingData = getRoutingData.as_dict()

                    carTraffictime = RoutingData['response']['route'][0][
                        'summary']['trafficTime']
                    carTraffictime = int(carTraffictime) / 60
                    time.sleep(0.1)

                    # if flag == 1:
                    #     getPRoutingData = ProutingApi.public_transport([lat, lng], [lat2, lng2], True, '2018-10-10T0'+str(hour)+':00:00',[herepy.RouteMode.publicTransport, herepy.RouteMode.fastest])
                    # if flag == 0:
                    #     getPRoutingData = ProutingApi.public_transport([lat, lng], [lat2, lng2], True,'2018-10-10T' + str(hour) + ':00:00',[herepy.RouteMode.publicTransport,herepy.RouteMode.fastest])
                    #
                    # PublicRoutingData = getPRoutingData.as_dict()
                    #
                    # PTbasetime = PublicRoutingData['response']['route'][0]['summary']['baseTime']
                    # PTbasetime = int(PTbasetime) / 60
                    # time.sleep(0.1)

                    data.loc[i, title] = carTraffictime
                # data.loc[i, 'Car'] = carTraffictime
                except:
                    data.loc[i, title] = 'Retry'

        return data
Esempio n. 18
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,
Esempio n. 19
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()
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']
import pandas as pd
import numpy as np
import datetime
from get_optimum_route import *
import herepy

routingApi = herepy.RoutingApi('YOUR_API_KEY')
"""
#-------------------------------- Modify columns --------------------------
data = pd.read_csv('updated_data_task.csv')
new_data = pd.DataFrame(columns=[])
new_data['Serial Number'] = data['Serial Number']

# Modify start_time and end_time to separate the date and time
for i in range(len(data.start_time)):
	if not pd.isnull(data.loc[i,'start_time']):
		date = datetime.datetime.strptime(data.loc[i,'start_time'], "%m/%d/%y  %H:%M")
		new_data.loc[new_data['Serial Number']==data['Serial Number'].iloc[i],'start_date'] = date.date()
		new_data.loc[new_data['Serial Number']==data['Serial Number'].iloc[i],'start_time'] = date.time()
	if not pd.isnull(data.loc[i,'end_time']):
		date = datetime.datetime.strptime(data.loc[i,'end_time'], "%m/%d/%y  %H:%M")
		new_data.loc[new_data['Serial Number']==data['Serial Number'].iloc[i],'end_date'] = date.date()
		new_data.loc[new_data['Serial Number']==data['Serial Number'].iloc[i],'end_time'] = date.time()

# Convert source service time to hours
for i in range(len(data.source_service_time)):
	if not pd.isnull(data.loc[i,'source_service_time']):
		temp = data.loc[i,'source_service_time'].split()
		
		time = datetime.datetime.strptime(temp[2].split('.')[0], "%H:%M:%S")
		time_tohours = time.hour + time.minute/60 + time.second/3600
Esempio n. 22
0
 def setUp(self):
     api = herepy.RoutingApi('app_id', 'app_code')
     self._api = api
Esempio n. 23
0
def get_distance_timetotravel(start, dest):
    trig = 0
    print(start, '---to---', dest, "  : ", end="")
    start = get_lat_long(start)
    dest = get_lat_long(dest)
    numbers = [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
    ]
    travel_time = 0
    traffic_time = 0
    distance = 0
    if start[0] == dest[0] == 1:
        dist_string = "The trip takes"

        try:
            routingApi = herepy.RoutingApi('dy8kVG3quHsuzvzE2IPe',
                                           'krzVA06TkOKIp6Km2Jkdiw')
            response = routingApi.car_route(
                [start[1], start[2]], [dest[1], dest[2]],
                [herepy.RouteMode.car, herepy.RouteMode.fastest])

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

            for i in range(reslen, 10, -1):
                if response[i - 10:i] == "travelTime":
                    time = ""
                    for j in range(i + 3, i + 10):
                        if response[j] not in numbers:
                            break
                        time = time + response[j]
                    travel_time = int(time)
                    break

            for i in range(reslen, 11, -1):
                if response[i - 11:i] == "trafficTime":
                    time = ""
                    for j in range(i + 3, i + 10):
                        if response[j] not in numbers:
                            break
                        time = time + response[j]
                    traffic_time = int(time)
                    break

            for i in range(reslen, len(dist_string), -1):
                if response[i - len(dist_string):i] == "The trip takes":
                    dist = ""
                    for j in range(i + 24, i + 34):
                        if response[j] == 'k':
                            break
                        dist = dist + response[j]
                    distance = float(dist)
                    break
            trig = 1
        except:
            trig = 0
    print(distance, ",", trig)
    return (trig, distance, travel_time, traffic_time)
Esempio n. 24
0
import herepy
import json

routingApi = herepy.RoutingApi('API_KEY')

def get_min_duration(src, dest):
    response = routingApi.car_route([src['latitude'], src['longitude']],
                                [dest['latitude'], dest['longitude']],
                                [herepy.RouteMode.car, herepy.RouteMode.fastest])
    result = json.load(response)
    return result['routes']['sections'][0]['summary']['duration']
Esempio n. 25
0
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 14:53:35 2020

@author: Biani Masita
"""

#Input Data 1: Distance Table
import herepy
import numpy as np
import pandas as pd
herepy.here_enum.MatrixSummaryAttribute
routingApi = herepy.RoutingApi('iqR92YoaCji_Y8hsq_tcAYyPDIk576xNZ6njsPuq3KM')
X_coordinate = [15, 76, 76, 96, 8, 54, 85, 74, 63, 63, 71, 71, 93, 57, 57]
Y_coordinate = [88, 57, 57, 62, 63, 22, 33, 62, 54, 54, 86, 86, 79, 58, 58]

# Read Depots and Incidents Coordinates

response = routingApi.matrix(
    start_waypoints=[[-6.217384, 106.932765], [-6.171159, 106.786711]],
    destination_waypoints=[[-6.171716, 106.800519], [-6.138936, 106.693909]],
    departure='2013-07-04T17:00:00+02',
    modes=[herepy.RouteMode.fastest, herepy.RouteMode.car],
    summary_attributes=['distance'])

Distance_table = np.zeros((15, 15))
list_incident = list(range(15))

for index1 in list_incident:
    for index2 in list_incident:
        Distance_table[index1, index2] = (