示例#1
0
 def test_encodeparameters(self):
     data = None
     encodedParameters = Utils.encode_parameters(data)
     self.assertEqual(encodedParameters, None)
     data = {"searchtext": "200 S Mathilda Sunnyvale CA"}
     encodedParameters = Utils.encode_parameters(data)
     self.assertTrue(encodedParameters)
     data = {"searchtext": "200 S Mathilda Sunnyvale CA", "gen": "8"}
     encodedParameters = Utils.encode_parameters(data)
     self.assertTrue(encodedParameters)
示例#2
0
 def test_encodeparameters(self):
     data = None
     encodedParameters = Utils.encode_parameters(data)
     self.assertEqual(encodedParameters, None)
     data = {'searchtext': '200 S Mathilda Sunnyvale CA'}
     encodedParameters = Utils.encode_parameters(data)
     self.assertTrue(encodedParameters)
     data = {'searchtext': '200 S Mathilda Sunnyvale CA', 'gen': '8'}
     encodedParameters = Utils.encode_parameters(data)
     self.assertTrue(encodedParameters)
示例#3
0
    def match_route(self,
                    gpx_file_content: str,
                    route_mode: str = "car",
                    pde_layers: List[str] = []) -> Optional[RmeResponse]:
        """Retrieves misc information about the route given in gpx file
        Args:
          gpxfile content (str):
            gpx file content as string
          routemode (str):
            route mode ('car')
          pde_layers (str list):
            PDE layers to retrieve e.g.:
              ROAD_GEOM_FCn(TUNNEL)
              SPEED_LIMITS_FCn(FROM_REF_SPEED_LIMIT,TO_REF_SPEED_LIMIT)
              ADAS_ATTRIB_FCn(SLOPES)

              or e.g.,

              ROAD_GEOM_FCn(*)
              SPEED_LIMITS_FCn(*)
        Returns:
          RmeResponse
        Raises:
          HEREError"""

        data = {
            "file": Utils.get_zipped_base64(gpx_file_content),
            "routemode": route_mode,
            "attributes": ",".join(pde_layers),
            "apikey": self._api_key,
        }
        return self.__get(data)
示例#4
0
    def match_route(self, gpx_file_content, route_mode='car', pde_layers=[]):
        """Retrieves misc information about the route given in gpx file
        Args:
          gpxfile content (str):
            gpx file content as string
          routemode (str):
            route mode ('car')
          pde_layers (str list):
            PDE layers to retrieve e.g.:
              ROAD_GEOM_FCn(TUNNEL)
              SPEED_LIMITS_FCn(FROM_REF_SPEED_LIMIT,TO_REF_SPEED_LIMIT)
              ADAS_ATTRIB_FCn(SLOPES)
              
              or e.g.,

              ROAD_GEOM_FCn(*)
              SPEED_LIMITS_FCn(*)
        Returns:
          RmeResponse
        Raises:
          HEREError"""

        data = {
            'file': Utils.get_zipped_base64(gpx_file_content),
            'route_mode': route_mode,
            'attributes': ','.join(pde_layers),
            'app_id': self._app_id,
            'app_code': self._app_code
        }
        return self.__get(data)
    def forecast_astronomy(self,
                           destination,
                           product=WeatherProductType.observation):
        """Request forecast for given destination.
        Args:
          destination (str):
            Destination name.
          product (str):
            A parameter identifying the type of report to obtain. Default value `observation`.
        Returns:
          DestinationWeatherResponse instance or HEREError
        """

        data = {
            'app_id': self._app_id,
            'app_code': self._app_code,
            'product': product.__str__(),
            'name': destination
        }
        url = Utils.build_url(self._base_url, extra_params=data)
        response = requests.get(url, timeout=self._timeout)
        json_data = json.loads(response.content.decode('utf8'))
        if json_data.get(self._product_node(product)) != None:
            return DestinationWeatherResponse.new_from_jsondict(
                json_data, param_defaults={self._product_node(product): None})
        else:
            return HEREError(
                json_data.get(
                    'Message',
                    'Error occured on ' + sys._getframe(1).f_code.co_name))
示例#6
0
 def __get(
     self,
     base_url,
     data,
     key,
     response_cls,
     manipulation_key: str = None,
     keys_for_manipulation: List = None,
 ):
     url = Utils.build_url(base_url, extra_params=data)
     if manipulation_key and keys_for_manipulation:
         for k in keys_for_manipulation:
             url = url.replace(k, manipulation_key)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if response.status_code == requests.codes.OK:
         if json_data.get(key) is not None:
             return response_cls.new_from_jsondict(json_data)
         else:
             raise error_from_routing_service_error(json_data)
     else:
         raise HEREError("Error occurred on routing_api __get " +
                         sys._getframe(1).f_code.co_name +
                         " response status code " +
                         str(response.status_code))
示例#7
0
 def __get(self, url, data):
     url = Utils.build_url(url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response._content.decode("utf8"))
     if json_data.get("TRAFFIC_ITEMS") != None:
         return TrafficIncidentResponse.new_from_jsondict(
             json_data,
             param_defaults={
                 "TIMESTAMP": None,
                 "VERSION": None,
                 "TRAFFIC_ITEMS": None,
                 "EXTENDED_COUNTRY_CODE": None,
                 "error": None,
             })
     elif json_data.get("RWS") != None:
         return TrafficFlowResponse.new_from_jsondict(
             json_data,
             param_defaults={
                 "RWS": None,
                 "CREATED_TIMESTAMP": None,
                 "VERSION": None,
                 "UNITS": None,
             })
     elif json_data.get("Response") != None:
         return TrafficFlowAvailabilityResponse.new_from_jsondict(
             json_data, param_defaults={"Response": None})
     else:
         error = self.__get_error_from_response(json_data)
         raise error
示例#8
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('response') != None:
         return RoutingResponse.new_from_jsondict(json_data)
     else:
         raise error_from_routing_service_error(json_data)
示例#9
0
 def __get(self, base_url, data, response_cls):
     url = Utils.build_url(base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if json_data.get("evStations") is not None:
         return response_cls.new_from_jsondict(json_data)
     else:
         raise error_from_ev_charging_service_error(json_data)
示例#10
0
 def __get_categories(self, data):
     url = Utils.build_url(self._base_url + 'categories/places', extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('items') != None:
         return PlaceCategoriesResponse.new_from_jsondict(json_data)
     else:
         raise HEREError(json_data.get('message', 'Error occured on ' + sys._getframe(1).f_code.co_name))
示例#11
0
 def test_buildurl(self):
     data = {
         'searchtext': '200 S Mathilda Sunnyvale CA',
         'app_id': 'app_id',
         'app_code': 'app_code'
     }
     url = Utils.build_url(
         'https://geocoder.cit.api.here.com/6.2/geocode.json', data)
     self.assertTrue(url)
示例#12
0
 def test_buildurl(self):
     data = {
         "searchtext": "200 S Mathilda Sunnyvale CA",
         "app_id": "app_id",
         "app_code": "app_code",
     }
     url = Utils.build_url(
         "https://geocoder.cit.api.here.com/6.2/geocode.json", data
     )
     self.assertTrue(url)
示例#13
0
 def _get(self, data, product):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if json_data.get(self._product_node(product)) != None:
         return DestinationWeatherResponse.new_from_jsondict(
             json_data, param_defaults={self._product_node(product): None})
     else:
         error = self._get_error_from_response(json_data)
         raise error
示例#14
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('response') != None:
         return RoutingResponse.new_from_jsondict(json_data)
     else:
         return HEREError(
             json_data.get(
                 'details',
                 'Error occured on ' + sys._getframe(1).f_code.co_name))
示例#15
0
 def __get(self, data, path, headers=None):
     url = Utils.build_url(self._base_url + path, extra_params=data)
     if headers != None:
         response = requests.get(url, timeout=self._timeout, headers=headers)
     else:
         response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('results') != None:
         return PlacesResponse.new_from_jsondict(json_data)
     else:
         raise HEREError(json_data.get('message', 'Error occured on ' + sys._getframe(1).f_code.co_name))
示例#16
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('suggestions') != None:
         return GeocoderAutoCompleteResponse.new_from_jsondict(json_data)
     else:
         raise HEREError(
             json_data.get(
                 'error_description',
                 'Error occured on ' + sys._getframe(1).f_code.co_name))
示例#17
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     try:
         json_data = json.loads(response.content.decode('utf8'))
         if json_data.get('Response') != None:
             return GeocoderResponse.new_from_jsondict(json_data)
         else:
             raise HEREError(json_data.get('Details', 'Error occured on function ' + sys._getframe(1).f_code.co_name))
     except ValueError as err:
         raise HEREError('Error occured on function ' + sys._getframe(1).f_code.co_name + ' ' + str(err))
示例#18
0
 def __get(self, data, path, json_node):
     url = Utils.build_url(self._base_url + path, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_node in json_data.get('Res', {}):
         return PublicTransitResponse.new_from_jsondict(json_data)
     elif 'text' in json_data.get('Res', {}).get('Message', {}):
         return HEREError(
             json_data['Res']['Message']['text'],
             'Error occured on ' + sys._getframe(1).f_code.co_name)
     else:
         return HEREError('Error occured on ' +
                          sys._getframe(1).f_code.co_name)
示例#19
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if json_data.get("items") != None:
         return PlacesResponse.new_from_jsondict(json_data)
     elif "error" in json_data:
         if json_data["error"] == "Unauthorized":
             raise UnauthorizedError(json_data["error_description"])
     else:
         raise HEREError(
             json_data.get(
                 "message",
                 "Error occurred on " + sys._getframe(1).f_code.co_name))
示例#20
0
 def __get(self, url, data, json_key):
     url = Utils.build_url(url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if json_data.get(json_key) != None and json_data.get(
             "isolines") != None:
         return IsolineRoutingResponse.new_from_jsondict(json_data,
                                                         param_defaults={
                                                             json_key: None,
                                                             "isolines":
                                                             None
                                                         })
     else:
         error = self.__get_error_from_response(json_data)
         raise error
示例#21
0
 def __get(self, data, path, json_node):
     url = Utils.build_url(self._base_url + path, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if json_node in json_data.get("Res", {}):
         return PublicTransitResponse.new_from_jsondict(json_data)
     elif "text" in json_data.get("Res", {}).get("Message", {}):
         raise HEREError(
             json_data["Res"]["Message"]["text"],
             "Error occurred on " + sys._getframe(1).f_code.co_name,
         )
     elif "error" in json_data:
         if json_data["error"] == "Unauthorized":
             raise UnauthorizedError(json_data["error_description"])
     else:
         raise HEREError("Error occurred on " +
                         sys._getframe(1).f_code.co_name)
示例#22
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     try:
         json_data = json.loads(response.content.decode("utf8"))
         if json_data.get("TracePoints") != None:
             return RmeResponse.new_from_jsondict(json_data)
         else:
             raise HEREError(
                 json_data.get(
                     "Details",
                     "Error occurred on function " +
                     sys._getframe(1).f_code.co_name,
                 ))
     except ValueError as err:
         raise HEREError("Error occurred on function " +
                         sys._getframe(1).f_code.co_name + " " + str(err))
示例#23
0
 def __get(
     self,
     base_url,
     data,
     key,
     response_cls,
     manipulation_key: str = None,
     keys_for_manipulation: List = None,
 ):
     url = Utils.build_url(base_url, extra_params=data)
     if manipulation_key and keys_for_manipulation:
         for k in keys_for_manipulation:
             url = url.replace(k, manipulation_key)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if json_data.get(key) is not None:
         return response_cls.new_from_jsondict(json_data)
     else:
         raise error_from_routing_service_error(json_data)
示例#24
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     try:
         json_data = json.loads(response.content.decode("utf8"))
         if json_data.get("items") != None:
             return GeocoderReverseResponse.new_from_jsondict(json_data)
         elif "error" in json_data:
             if json_data["error"] == "Unauthorized":
                 raise UnauthorizedError(json_data["error_description"])
         else:
             raise HEREError(
                 json_data.get(
                     "Details",
                     "Error occurred on function " +
                     sys._getframe(1).f_code.co_name,
                 ))
     except ValueError as err:
         raise HEREError("Error occurred on function " +
                         sys._getframe(1).f_code.co_name + " " + str(err))
示例#25
0
    def forecast_astronomy(self, destination):
        """Request forecast for given destination.
        Args:
          destination (str):
            Destination name.
        Returns:
          DestinationWeatherResponse instance or HEREError
        """

        data = {
            'app_id': self._app_id,
            'app_code': self._app_code,
            'product': destination
        }
        url = Utils.build_url(self._base_url, extra_params=data)
        response = requests.get(url, timeout=self._timeout)
        json_data = json.loads(response.content.decode('utf8'))
        if json_data.get('astronomy') != None:
            return DestinationWeatherResponse.new_from_jsondict(json_data)
        else:
            return HEREError(
                json_data.get(
                    'Message',
                    'Error occured on ' + sys._getframe(1).f_code.co_name))
示例#26
0
    def get_vectortile(
        self,
        latitude: float,
        longitude: float,
        zoom: int,
        layer: VectorMapTileLayer = VectorMapTileLayer.base,
        projection: str = "mc",
        tile_format: str = "omv",
        query_parameters: Optional[Dict] = None,
        headers: Optional[Dict] = None,
    ) -> Optional[bytes]:
        """Retrieves the protocol buffer encoded binary tile.
        Args:
          latitude (float):
            Latitude value to be used to fetch map tile.
          longitude (float):
            Longitude value to be used to fetch map tile.
          zoom (int):
            Specifies the tile Zoom level. Accepted values range from 0-17. minimum - 0, maximum - 17.
          layer (VectorMapTileLayer):
            Specifies the layers available in the tile. The access to each layer is determined by the contract of the user.
          projection (str):
            Specifies the tile projection. mc - Mercator Projection.
          tile_format (str):
            Specifies the tile format.
            omv - Optimized Map for Visualization (follows Map Vector Tile open specification).
          query_parameters (Optional[Dict]):
            Optional Query Parameters. Refer to the API definition for values.
          headers (Optional[Dict]):
            Optional headers. Refer to the API definition for values.
        Returns:
          Vector tile as bytes.
        Raises:
          HEREError
        """

        column, row = MercatorProjection.get_column_row(latitude=latitude,
                                                        longitude=longitude,
                                                        zoom=zoom)
        url = str.format(
            self._base_url + "{}/{}/{}/{}/{}/{}",
            layer.__str__(),
            projection,
            zoom,
            column,
            row,
            tile_format,
        )
        if query_parameters:
            query_parameters.update({"apiKey": self._api_key})
        else:
            query_parameters = {"apiKey": self._api_key}
        url = Utils.build_url(url, extra_params=query_parameters)
        response = requests.get(url,
                                headers=headers,
                                timeout=self._timeout,
                                stream=True)
        if isinstance(response.content, bytes):
            try:
                json_data = json.loads(response.content.decode("utf8"))
                if "error" in json_data:
                    error = self.__get_error_from_response(json_data)
                    raise error
            except UnicodeDecodeError as err:
                print("Vector tile downloaded")
        return response.content
示例#27
0
    def get_mapimage(
        self,
        top_left: List[float] = None,
        bottom_right: List[float] = None,
        coordinates: List[float] = None,
        city_name: Optional[str] = None,
        country_name: Optional[str] = None,
        center: List[float] = None,
        encoded_geo_coordinate: str = None,
        encoded_geo_center_coordinate: str = None,
        image_format: MapImageFormatType = MapImageFormatType.png,
        image_height: Optional[int] = None,
        show_position: bool = False,
        maxhits: int = 1,
        label_language: str = "eng",
        second_label_language: Optional[str] = None,
        house_number: Optional[str] = None,
        zoom: int = 8,
        map_scheme: Optional[int] = None,
        uncertainty: Optional[str] = None,
        nodot: Optional[bool] = None,
    ):
        """Retrieves the map image with given parameters.
        Args:
          top_left (List[float]):
            List contains latitude and longitude in order for the bounding box parameter.
            Note: If poi or poix are given, then this parameter is ignored.
            Note: If this parameter is provided, it ignores tx, tx.xy, ctr, ectr.
            Note: If this parameter is provided then the geo search parameters are ignored, such as co.
          bottom_right (List[float]):
            List contains latitude and longitude in order for the bounding box parameter.
            Note: If poi or poix are given, then this parameter is ignored.
            Note: If this parameter is provided, it ignores tx, tx.xy, ctr, ectr.
            Note: If this parameter is provided then the geo search parameters are ignored, such as co.
          coordinates (List[float]):
            List contains latitude and longitude in order.
          city_name (Optional[str]):
            City name for address based search. UTF-8 encoded and URL-encoded.
          country_name (Optional[str]):
            Country name for address based search. UTF-8 encoded and URL-encoded.
          center (List[float]):
            Map center point geo coordinate. If the position is on the border of the map, the dot might be cropped.
          encoded_geo_coordinate (str):
            Encoded equivalent of position geo coordinate parameter c. Parameter c is ignored if this parameter is specified.
          encoded_geo_center_coordinate (str):
            Encoded equivalent of map center point geo coordinate parameter ctr. Parameter ctr is ignored if this parameter is present.
          image_format (MapImageFormatType):
            Image format. It is possible to request the map image.
          image_height (Optional[int]):
            Result image height in pixels, maximum 2048. Height and width parameter can be provided independently,
            i.e. there is no need to enter both to resize the image.
          show_position (bool):
            Flag for showing address or position information box inside the map image
            (if address is available or position is allowed to be shown).
            Note: If geo search parameters such as co are provided, then the information shown
            is related to those parameter's values, if valid.
          maxhits (int):
            Maximum number of search results to return. Applies only when some kind of search
            is performed which can return multiple results. Set to 1 to show directly the first
            matching result without any results listing.
          label_language (str):
            Map label language. Specifies the language to be used to display descriptions of details inside the map image.
            If the parameter is not provided, the default language depends on the highest prioritized locale of the
            client's Accept-Language HTTP header which is currently supported.
            If no map language based on HTTP header can be determined, the server configured default is used.
            Note: Some MARC three-letter language codes are supported, please check https://developer.here.com/documentation/map-image/dev_guide/topics/resource-map.html
            for more details.
          second_label_language (Optional[str]):
            Second language to be used, only for dual labelling, therefore a ml language must also be present Map label language.
            Note: Some MARC three-letter language codes are supported, please check https://developer.here.com/documentation/map-image/dev_guide/topics/resource-map.html
            for more details.
          house_number (Optional[str]):
            House number on the street for address based search.
          zoom (int):
            Zoom level for the map image.
          map_scheme (Optional[int]):
            Determines the map scheme to use for the map image.
          uncertainty (Optional[str]):
            The parameter u specifies position uncertainty, which is shown as a filled circle around a
            location defined in terms of its latitude and longitude. The value of the parameter u indicates
            the radius of the circle representing uncertainty. In this case, the radius is set to 5 myriameters,
            which is 50000 meters.
          nodot (Optional[bool]):
            If provided map image will be without dots.
        Returns:
          Map image as bytes.
        Raises:
          HEREError
        """

        data = {
            "z": zoom,
            "apiKey": self._api_key,
        }
        if top_left and bottom_right:
            data["bbox"] = str.format(
                "{0},{1};{2},{3}",
                top_left[0],
                top_left[1],
                bottom_right[0],
                bottom_right[1],
            )
        if coordinates:
            data["c"] = str.format("{0},{1}", coordinates[0], coordinates[1])
        if city_name:
            data["ci"] = city_name
        if country_name:
            data["co"] = country_name
        if center:
            data["ctr"] = str.format("{0},{1}", center[0], center[1])
        if encoded_geo_coordinate:
            data["e"] = encoded_geo_coordinate
        if encoded_geo_center_coordinate:
            data["ectr"] = encoded_geo_center_coordinate
        if map_scheme:
            data["t"] = map_scheme
        if uncertainty:
            data["u"] = uncertainty
        if nodot:
            data["nodot"] = None
        if image_height:
            data["h"] = image_height
        if house_number:
            data["n"] = house_number
        data["f"] = image_format._value_
        data["i"] = show_position
        data["maxhits"] = maxhits
        data["ml"] = label_language
        if second_label_language:
            data["ml2"] = second_label_language
        url = Utils.build_url(self._base_url, extra_params=data)
        response = requests.get(url, timeout=self._timeout)
        if isinstance(response.content, bytes):
            try:
                json_data = json.loads(response.content.decode("utf8"))
                if "error" in json_data:
                    error = self.__get_error_from_response(json_data)
                    raise error
            except UnicodeDecodeError as err:
                print("Map image downloaded")
        return response.content
示例#28
0
    def sync_matrix(
        self,
        origins: Union[List[float], str],
        destinations: Union[List[float], str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: Optional[List[float]] = None,
        radius: Optional[int] = None,
        profile: Optional[MatrixRoutingProfile] = None,
        departure: str = None,
        routing_mode: Optional[MatrixRoutingMode] = None,
        transport_mode: Optional[MatrixRoutingTransportMode] = None,
        avoid: Optional[Avoid] = None,
        truck: Optional[Truck] = None,
        matrix_attributes: Optional[List[MatrixSummaryAttribute]] = None,
    ) -> Optional[RoutingMatrixResponse]:
        """Sync request a matrix of route summaries between M starts and N destinations.
        Args:
          origins (List):
            List of lists of coordinates [lat,long] of start waypoints.
            or list of string with the location names.
          destinations (List):
            List of lists of coordinates [lat,long] of destination waypoints.
            or list of string with the location names.
          matrix_type (MatrixRoutingType):
            Routing type used in definition of a region in which the matrix will be calculated.
          center (Optional[List]):
            Center of region definition, latitude and longitude.
          radius (Optional[int]):
            Center  of region definition.
          profile (Optional[MatrixRoutingProfile]):
            A profile ID enables the calculation of matrices with routes of arbitrary length.
          departure (str):
            time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
          routing_mode (Optional[MatrixRoutingMode]):
            Route mode used in optimization of route calculation.
          transport_mode (Optional[MatrixRoutingTransportMode]):
            Depending on the transport mode special constraints, speed attributes and weights
            are taken into account during route calculation.
          avoid (Optional[Avoid]):
            Avoid routes that violate these properties.
          truck (Optional[Truck]):
            Different truck options to use during route calculation when transportMode = truck.
          matrix_attributes (List):
            List of MatrixSummaryAttribute enums.
        Returns:
          RoutingMatrixResponse
        Raises:
          HEREError: If an error is received from the server.
        """

        query_params = {
            "apiKey": self._api_key,
            "async": "false",
        }

        request_body = self.__prepare_matrix_request_body(
            origins=origins,
            destinations=destinations,
            matrix_type=matrix_type,
            center=center,
            radius=radius,
            profile=profile,
            departure=departure,
            routing_mode=routing_mode,
            transport_mode=transport_mode,
            avoid=avoid,
            truck=truck,
            matrix_attributes=matrix_attributes,
        )

        url = Utils.build_url(self.URL_CALCULATE_MATRIX,
                              extra_params=query_params)
        headers = {"Content-Type": "application/json"}
        response = requests.post(url,
                                 json=request_body,
                                 headers=headers,
                                 timeout=self._timeout)
        json_data = json.loads(response.content.decode("utf8"))
        if response.status_code == requests.codes.OK:
            if json_data.get("matrix") is not None:
                return RoutingMatrixResponse.new_from_jsondict(json_data)
            else:
                raise HEREError("Error occurred on routing_api sync_matrix " +
                                sys._getframe(1).f_code.co_name +
                                " response status code " +
                                str(response.status_code))
        else:
            if "title" in json_data and "cause" in json_data:
                raise HEREError(
                    str.format(
                        "routing_api sync_matrix failed! title: {0}, cause: {1}",
                        json_data["title"],
                        json_data["cause"],
                    ))
            else:
                raise HEREError("Error occurred on routing_api sync_matrix " +
                                sys._getframe(1).f_code.co_name)
示例#29
0
    def get_maptile(
        self,
        latitude: float,
        longitude: float,
        zoom: int,
        api_type: MapTileApiType = MapTileApiType.base,
        resource_type: MapTileResourceType = BaseMapTileResourceType.
        alabeltile,
        map_id: str = "newest",
        scheme: str = "normal.day",
        size: int = 256,
        tile_format: str = "png8",
        query_parameters: Optional[Dict] = None,
    ) -> Optional[bytes]:
        """Returns optional bytes value of map tile with given parameters.
        Args:
          latitude (float):
            Latitude value to be used to fetch map tile.
          longitude (float):
            Longitude value to be used to fetch map tile.
          zoom (int):
            Zoom level of the map image.
          api_type (MapTileApiType):
            MapTileApiType used to generate url.
          resource_type (MapTileResourceType):
            Resource type to download map tile.
          map_id (str):
            Specifies the map version, either newest or with a hash value.
            https://developer.here.com/documentation/map-tile/dev_guide/topics/map-versions.html
          scheme (str):
            Specifies the view scheme. A complete list of the supported schemes may be obtained
            by using the https://developer.here.com/documentation/map-tile/dev_guide/topics/resource-info.html
            resource.
          size (int):
            Returned image size. The following sizes ([width, height]) are supported:
            256 = [256, 256]
            512 = [512, 512]
            The following sizes ([width, height]) are deprecated, although usage is still accepted:
            128 = [128, 128]
          tile_format (str):
            Returned image format. The following image formats are supported:
            png – PNG format, 24 bit, RGB
            png8 – PNG format, 8 bit, indexed color
            jpg – JPG format at 90% quality
            Please note that JPG is recommended for satellite and hybrid schemes only.
          query_parameters (Optional[Dict]):
            Optional Query Parameters. Refer to the API definition for values.
        Returns:
          Map tile as bytes.
        Raises:
          HEREError
        """

        server = randrange(1, 4)
        column, row = MercatorProjection.get_column_row(latitude=latitude,
                                                        longitude=longitude,
                                                        zoom=zoom)
        url = str.format(
            "https://{}.{}.maps.ls.hereapi.com/maptile/2.1/{}/{}/{}/{}/{}/{}/{}/{}",
            server,
            api_type.__str__(),
            resource_type.__str__(),
            map_id,
            scheme,
            zoom,
            column,
            row,
            size,
            tile_format,
        )
        if query_parameters:
            query_parameters.update({"apiKey": self._api_key})
        else:
            query_parameters = {"apiKey": self._api_key}
        url = Utils.build_url(url, extra_params=query_parameters)
        response = requests.get(url, timeout=self._timeout, stream=True)
        if isinstance(response.content, bytes):
            try:
                json_data = json.loads(response.content.decode("utf8"))
                if "error" in json_data:
                    error = self.__get_error_from_response(json_data)
                    raise error
            except UnicodeDecodeError as err:
                print("Map tile downloaded")
        return response.content
示例#30
0
    def async_matrix(
        self,
        token: str,
        origins: Union[List[float], str],
        destinations: Union[List[float], str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: Optional[List[float]] = None,
        radius: Optional[int] = None,
        profile: Optional[MatrixRoutingProfile] = None,
        departure: str = None,
        routing_mode: Optional[MatrixRoutingMode] = None,
        transport_mode: Optional[MatrixRoutingTransportMode] = None,
        avoid: Optional[Avoid] = None,
        truck: Optional[Truck] = None,
        matrix_attributes: Optional[List[MatrixSummaryAttribute]] = None,
    ) -> Optional[RoutingMatrixResponse]:
        """Async request a matrix of route summaries between M starts and N destinations.
        Args:
          token (str):
            Bearer token required for async calls. This is the only working solution for now.
            How to create a bearer token:
            https://developer.here.com/documentation/identity-access-management/dev_guide/topics/sdk.html#step-1-register-your-application
            https://developer.here.com/documentation/identity-access-management/dev_guide/topics/postman.html
          origins (List):
            List of lists of coordinates [lat,long] of start waypoints.
            or list of string with the location names.
          destinations (List):
            List of lists of coordinates [lat,long] of destination waypoints.
            or list of string with the location names.
          matrix_type (MatrixRoutingType):
            Routing type used in definition of a region in which the matrix will be calculated.
          center (Optional[List]):
            Center of region definition, latitude and longitude.
          radius (Optional[int]):
            Center  of region definition.
          profile (Optional[MatrixRoutingProfile]):
            A profile ID enables the calculation of matrices with routes of arbitrary length.
          departure (str):
            time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
          routing_mode (Optional[MatrixRoutingMode]):
            Route mode used in optimization of route calculation.
          transport_mode (Optional[MatrixRoutingTransportMode]):
            Depending on the transport mode special constraints, speed attributes and weights
            are taken into account during route calculation.
          avoid (Optional[Avoid]):
            Avoid routes that violate these properties.
          truck (Optional[Truck]):
            Different truck options to use during route calculation when transportMode = truck.
          matrix_attributes (List):
            List of MatrixSummaryAttribute enums.
        Returns:
          RoutingMatrixResponse.
        Raises:
          HEREError: If an error is received from the server.
        """

        query_params = {}

        request_body = self.__prepare_matrix_request_body(
            origins=origins,
            destinations=destinations,
            matrix_type=matrix_type,
            center=center,
            radius=radius,
            profile=profile,
            departure=departure,
            routing_mode=routing_mode,
            transport_mode=transport_mode,
            avoid=avoid,
            truck=truck,
            matrix_attributes=matrix_attributes,
        )

        url = Utils.build_url(self.URL_CALCULATE_MATRIX,
                              extra_params=query_params)
        headers = {
            "Content-Type": "application/json",
            "Authorization": str.format("Bearer {0}", token),
        }
        json_data = json.dumps(request_body)
        response = requests.post(url,
                                 json=request_body,
                                 headers=headers,
                                 timeout=self._timeout)
        if response.status_code == requests.codes.ACCEPTED:
            json_data = response.json()
            print("Matrix {} calculation {}".format(json_data["matrixId"],
                                                    json_data["status"]))
            poll_url = json_data["statusUrl"]
            headers = {"Authorization": str.format("Bearer {0}", token)}
            print("Polling matrix calculation started!")
            result = polling.poll(
                lambda: requests.get(poll_url, headers=headers),
                check_success=self.__is_correct_response,
                step=5,
                poll_forever=True,
            )
            print("Polling matrix calculation completed!")
            poll_data = result.json()
            return RoutingMatrixResponse.new_from_jsondict(poll_data)
        else:
            json_data = response.json()
            if (json_data.get("error") is not None
                    and json_data.get("error_description") is not None):
                raise HEREError("Error occurred on async_matrix: " +
                                json_data["error"] + ", description: " +
                                json_data["error_description"])
            elif (json_data.get("title") is not None
                  and json_data.get("cause") is not None):
                raise HEREError("Error occurred on async_matrix: " +
                                json_data["title"] + ", cause: " +
                                json_data["cause"])
            else:
                raise HEREError("Error occurred on async_matrix " +
                                sys._getframe(1).f_code.co_name)