Example #1
0
    def search(self, term=None, around=None,
               controller=DummyController(), maxResults=8 ,
               radius=constants.DEFAULT_LOCAL_SEARCH_RADIUS, **kwargs):
        """Search for POI using Google local search API"""
        if term is None and around is None:
            log.error("Google local search: term and location not set")
            return []
        elif term is None:
            log.error("Google local search: term not set")
            return []
        elif around is None:
            log.error("Google local search: location not set")
            return []
        controller.status = "online POI search"

        (query, location) = self._constructGLSQuery(term, around)

        sensor = 'false'
        if 'sensor' in kwargs:
            sensor = kwargs['sensor']
        log.info("Google local search query: %s" % query)
        gMap = _getGmapsInstance()
        if gMap:
            response = gMap.local_search(query, maxResults, location = location,
                                         sensor = sensor, radius=radius)
            controller.status = "processing POI from search"
            points = self._processGLSResponse(response)
            controller.status = "online POI search done"
            return points
        else:
            log.error("Google local search: no Google maps instance")
Example #2
0
 def search(self,
            waypoints,
            route_params=RouteParameters(),
            controller=DummyController()):
     # check if we have at least 2 points
     routingStart = time.time()
     if len(waypoints) < 2:
         log.error(
             "GoogleRouting provider: ERROR, need at least 2 points for routing"
         )
         return RoutingResult(None, route_params)
     start = waypoints[0]
     destination = waypoints[-1]
     inBetweenPoints = waypoints[1:-1]
     log.info("GoogleRouting: routing from %s to %s", start, destination)
     log.info(route_params)
     controller.status = "online routing in progress"
     route, returnCode, errorMessage = _googleDirections(
         start, destination, inBetweenPoints, route_params)
     controller.status = "online routing done"
     # return the data from the routing function and add elapsed time in ms
     return RoutingResult(route,
                          route_params,
                          returnCode=returnCode,
                          errorMessage=errorMessage,
                          lookupDuration=time.time() - routingStart)
Example #3
0
 def search(self, term=None, around=None, controller=DummyController(), **kwargs):
     """Search for an address using Google geocoding API"""
     if term is None:
         log.error("GoogleAddressSearch: term is None")
         return []
     controller.status = "starting online address search"
     controller.status = "online address search done"
Example #4
0
 def search(self, term=None, around=None, controller=DummyController(), **kwargs):
     """Search for Wikipedia articles around the given location"""
     if term is None:
         log.error("Nominatim Wikipedia search: term not set")
         return []
     controller.status = "online Wikipedia search"
     results = geonames.wikipediaSearch(term)
     controller.status = "online Wikipedia search done"
     return results
Example #5
0
 def search(self, term=None, around=None, controller=DummyController(), **kwargs):
     controller.status  = "starting provider test"
     log.debug("starting provider test")
     for i in range(1,7,1):
         controller.status = "waiting %d seconds" % i
         log.debug("waiting %d seconds" % i)
         time.sleep(1)
     controller.status = "provider test done"
     log.debug("provider test done")
     return None
Example #6
0
    def search(self,
               term=None,
               around=None,
               controller=DummyController(),
               **kwargs):
        """Search for an address using the OSM Scout Server geocoding API"""
        if term is None:
            log.error("OSMScoutServerSearch: term is None")
            return []
        results = []
        controller.status = "OSM Scout Server place search"
        try:
            term = term.encode("utf-8")
            params = {
                'limit': 16,  # TODO: make this configurable
                'search': term
            }
            queryUrl = OSM_SCOUT_SERVER_POI_SEARCH_URL + urlencode(params)
            reply = urlopen(queryUrl)
            if reply:
                # json in Python 3 really needs it encoded like this
                replyData = reply.read().decode("utf-8")
                jsonReply = json.loads(replyData)
                for result in jsonReply:
                    name = result.get("title")

                    # Summary generation is based on how Poor Maps does this
                    items = []
                    try:
                        poi_type = result["type"]
                        poi_type = poi_type.replace("amenity", "")
                        poi_type = poi_type.replace("_", " ").strip()
                        items.append(poi_type.capitalize())
                    except:
                        pass
                    try:
                        items.append(result["admin_region"])
                    except:
                        pass
                    summary = ", ".join(items) or "–"
                    lat = float(result["lat"])
                    lon = float(result["lng"])
                    # create Point object instance
                    point = Point(lat,
                                  lon,
                                  name=name,
                                  summary=summary,
                                  message=summary)
                    results.append(point)
        except Exception:
            log.exception("OSMScoutServerPlaceSearch: failed with exception")

        controller.status = "offline place search done"
        return results
Example #7
0
    def search(self,
               term=None,
               around=None,
               controller=DummyController(),
               **kwargs):
        """Search for an address for coordinates using the Nominatim
        reverse geocoding API
        """
        if term is None:
            log.error("Nominatim reverse geocoding: term is None")
            return []
        results = []
        controller.status = "starting online reverse geocoding"
        try:
            params = {
                'lat': term.lat,
                'lon': term.lon,
                'zoom': 18,
                'format': 'json',
                'addressdetails': 0
            }
            queryUrl = NOMINATIM_REVERSE_GEOCODING_URL + urlencode(params)
            reply = urlopen(queryUrl)
            if reply:
                # json in Python 3 really needs it encoded like this
                replyData = reply.read().decode("utf-8")
                result = json.loads(replyData)
                # split a prefix from the display name
                description = result.get("display_name")
                # get the first 2 elements for name
                name = description.split(", ")[0:2]
                name = ", ".join(name)
                # and first three elements for summary
                summary = description.split(", ")[0:3]
                # recombined back to ", " delimited string
                summary = ", ".join(summary)
                lat = float(result["lat"])
                lon = float(result["lon"])
                # create Point object instance
                point = Point(lat,
                              lon,
                              name=name,
                              summary=summary,
                              message=description)
                results.append(point)
        except Exception:
            log.exception("Nominatim reverse geocoding: failed with exception")

        controller.status = "online reverse geocoding done"
        return results
Example #8
0
    def search(self,
               waypoints,
               route_params=None,
               controller=DummyController()):
        routingStart = time.time()
        controller.status = "OSM Scout Server routing"
        try:
            route_type = "auto"  # car directions are the default
            if route_params.routeMode == constants.ROUTE_BIKE:
                route_type = "bicycle"
            elif route_params.routeMode == constants.ROUTE_PEDESTRIAN:
                route_type = "pedestrian"

            locations = []
            for waypoint in waypoints:
                location_dict = {'lat': waypoint.lat, 'lon': waypoint.lon}
                # include heading when available
                if waypoint.heading is not None:
                    location_dict["heading"] = waypoint.heading
                locations.append(location_dict)

            params = {
                'costing': route_type,
                'directions_options': {
                    'language': route_params.language
                },
                'locations': locations
            }
            queryUrl = OSM_SCOUT_SERVER_ROUTING_URL + "json=" + json.dumps(
                params)
            reply = urlopen(queryUrl)

            if reply:
                # json in Python 3 really needs it encoded like this
                replyData = reply.read().decode("utf-8")
                jsonReply = json.loads(replyData)
                if "API version" in jsonReply and jsonReply[
                        'API version'] == "libosmscout V1":
                    route = Way.from_osm_scout_json(jsonReply)
                else:
                    route = Way.from_valhalla(jsonReply)
                return RoutingResult(route,
                                     route_params,
                                     constants.ROUTING_SUCCESS,
                                     lookupDuration=time.time() - routingStart)
        except Exception:
            log.exception("OSM Scout Server routing: failed with exception")
Example #9
0
    def search(self,
               waypoints,
               route_params=None,
               controller=DummyController()):
        routingStart = time.time()
        if self._monav.data_path is not None:
            result = None
            try:
                if not self._monav.server_running:
                    controller.status = "starting Monav routing server"
                    self._monav.start_server()
                controller.status = "Monav offline routing in progress"
                log.info(route_params)
                result = self._monav.get_monav_directions(
                    waypoints, route_params)
                controller.status = "Monav offline routing done"
            except Exception:
                log.exception('Monav route lookup failed')

            if result is None:  # routing failed for unknown reasons
                return RoutingResult(None, route_params)
            if result.type == result.SUCCESS:
                # convert the Monav result to a Way object usable
                # for turn-by-turn navigation using the instruction
                # generator set in the Monav wrapper
                route = Way.from_monav_result(result)
                return RoutingResult(route,
                                     route_params,
                                     constants.ROUTING_SUCCESS,
                                     lookupDuration=time.time() - routingStart)
            elif result.type == result.LOAD_FAILED:
                return RoutingResult(None, route_params,
                                     constants.ROUTING_LOAD_FAILED)
            elif result.type == result.LOOKUP_FAILED:
                return RoutingResult(None, route_params,
                                     constants.ROUTING_LOOKUP_FAILED)
            elif result.type == result.ROUTE_FAILED:
                return RoutingResult(None, route_params,
                                     constants.ROUTING_ROUTE_FAILED)
            else:
                return RoutingResult(None, route_params)
        else:
            log.error("no Monav routing data - can't route")
            return RoutingResult(None, route_params, constants.ROUTING_NO_DATA)
Example #10
0
    def search(self, waypoints, routeParams=None, controller=DummyController()):
        # get mode based sub-folder
        routingStart = time.time()
        if self.monav.dataPath is not None:
            result = None
            try:
                if self.monav.monavServer is None:
                    controller.status = "starting Monav routing server"
                    self.monav.startServer()
                controller.status = "Monav offline routing in progress"
                result = self.monav.monavDirections(waypoints)
                controller.status = "Monav offline routing done"
            except Exception:
                log.exception('Monav route lookup failed')

            if result is None: # routing failed for unknown reasons
                return RoutingResult(None, routeParams)
            if result.type == result.SUCCESS:
                # convert the Monav result to a Way object usable
                # for turn-by-turn navigation using the instruction
                # generator set in the Monav wrapper
                route = way.fromMonavResult(result, self.monav.result2turns)
                return RoutingResult(route,
                                     routeParams,
                                     constants.ROUTING_SUCCESS,
                                     lookupDuration=time.time() - routingStart)
            elif result.type == result.LOAD_FAILED:
                return RoutingResult(None, routeParams, constants.ROUTING_LOAD_FAILED)
            elif result.type == result.LOOKUP_FAILED:
                return RoutingResult(None, routeParams, constants.ROUTING_LOOKUP_FAILED)
            elif result.type == result.ROUTE_FAILED:
                RoutingResult(None, routeParams, constants.ROUTING_ROUTE_FAILED)
            else:
                return RoutingResult(None, routeParams)
        else:
            log.error("no Monav routing data - can't route")
            RoutingResult(None, routeParams, constants.ROUTING_NO_DATA)
Example #11
0
    def search(self,
               term=None,
               around=None,
               controller=DummyController(),
               maxResults=8,
               radius=constants.DEFAULT_LOCAL_SEARCH_RADIUS,
               **kwargs):
        """Search for POI using OSM Scout Server"""
        if term is None and around is None:
            log.error(
                "OSM Scout Server local search: term and location not set")
            return []
        elif term is None:
            log.error("OSM Scout Server local search: term not set")
            return []
        elif around is None:
            log.error("OSM Scout Server local search: location not set")
            return []
        controller.status = "OSM Scout Server local search"

        results = []
        controller.status = "OSM Scout Server local search"
        try:
            point_type = "amenity"
            # check if type override has been specified by prefix
            term_split = term.split(":", 1)
            if len(term_split) > 1:
                point_type = term_split[0]
                term = term_split[1]

            term = term.encode("utf-8")
            params = {
                'limit': maxResults,
                'query': term,
                'radius': radius,
                'lat': around.lat,
                'lng': around.lon
            }
            query_url = OSM_SCOUT_SERVER_LOCAL_SEARCH_URL + urlencode(params)
            log.debug("OSM Scout Server local search query URL:")
            log.debug(query_url)
            reply = urlopen(query_url)
            if reply:
                # json in Python 3 really needs it encoded like this
                replyData = reply.read().decode("utf-8")
                jsonReply = json.loads(replyData)
                for result in jsonReply.get("results"):
                    name = result.get("title")

                    # Summary generation is based on how Poor Maps does this
                    items = []
                    try:
                        poi_type = result["type"]
                        poi_type = poi_type.replace("amenity", "")
                        poi_type = poi_type.replace("_", " ").strip()
                        items.append(poi_type.capitalize())
                    except:
                        pass
                    try:
                        items.append(result["admin_region"])
                    except:
                        pass
                    summary = ", ".join(items) or "–"
                    lat = float(result["lat"])
                    lon = float(result["lng"])
                    # create Point object instance
                    point = Point(lat,
                                  lon,
                                  name=name,
                                  summary=summary,
                                  message=summary)
                    results.append(point)
        except Exception:
            log.exception("OSMScoutServerPlaceSearch: failed with exception")

        controller.status = "offline place search done"
        return results