Routes between two or more coordinate points

Hi, i am new to graphHopper Api, i have been trying to integrate graphHopper Api to create a route api between two or more coordinates using Django, Python. what i have done is i have created a program where i could get any coordinates and created offset values manually for both coordinates and integrated a bounding box around those coordinates. Now the problem is when i run the program, the route provided by the program is disrupted, it provides a polyline but couldn’t reach destination and the route is random and plus when i change the coordinate like make source coordinates to destination and vice versa, the route path becomes totally disrupted I don’t know what i am doing wrong.

I think you should provide examples (Request parameters, Example Routes on, graphhopper config) to highlight what you mean by “disrupted” .
At least what I can tell you (which I basically very little) : Graphhopper is doing a mapping of start and destination to the underlying graph (i.e. road network for instance). So you can’t expect the start or destination to exactly match your request. It is only close nearby.

1 Like

basically what i meant to say was, the generate route from the provide coordinates is wrong that is, it couldn’t provide the route using the road network, what i have done is input small offset values for source coordinates as well as destination, created a bounding box after receiving the coordinates and after that applied offset to source and destination, and requested for graphHopperAPI, let me just provide you the code, i have implemented like this: @api_view([‘POST’])
def get_route(request):
offset_lat = 0.00000001 # Your desired latitude offset value
offset_lng = -0.00000001 # Your desired longitude offset value
if request.method == ‘POST’:
data = json.loads(request.body)
coordinates = data.get(‘coordinates’, [])
buffer_distance_km = 0.001

    if len(coordinates) < 2:
        return JsonResponse({'error': 'At least two coordinates are required.'}, status=400)
    # Calculate bounding box
    min_lat = min(coord['lat'] for coord in coordinates) - buffer_distance_km
    max_lat = max(coord['lat'] for coord in coordinates) + buffer_distance_km
    min_lng = min(coord['lng'] for coord in coordinates) - buffer_distance_km
    max_lng = max(coord['lng'] for coord in coordinates) + buffer_distance_km
    # Apply offset to source and destination coordinates (subtract offsets for reverse direction)
    offset_source = {'lat': coordinates[0]['lat'] - offset_lat, 'lng': coordinates[0]['lng'] - offset_lng}
    #offset_destination = {'lat': coordinates[-1]['lat'] - offset_lat, 'lng': coordinates[-1]['lng'] - offset_lng}
    offset_destination = {'lat': coordinates[-1]['lat'], 'lng': coordinates[-1]['lng']}

    print('offset source', offset_source)
    print('offset destination', offset_destination)

    graphhopper_url = ''
    #waypoints = [f"{coord['lat']},{coord['lng']}" for coord in offset_coordinates]
    waypoints = [f"{offset_source['lat']},{offset_source['lng']}", f"{offset_destination['lat']},{offset_destination['lng']}"]
    #bbox = f"{min_lng},{min_lat},{max_lng},{max_lat}" if offset_lat < 0 else f"{min_lng},{max_lat},{max_lng},{min_lat}"
    params = {
        'point': waypoints,
        'vehicle': 'car',
        'key': 'key provided',
        'weighting': 'fastest',
        'bbox': f"{min_lng},{min_lat},{max_lng},{max_lat}",  # Add bounding box parameter
        #'bbox': bbox,
    response = requests.get(graphhopper_url, params=params)

    if response.status_code == 200:
        routing_data = response.json() 
        print('Routing data', routing_data)

        #route_coordinates = routing_data.get('paths', [])[0].get('points', [])  # Extract the route coordinates
        # Extract the points string from the API response
    paths = routing_data.get('paths', [])
    if paths:
        points_encoded = paths[0].get('points_encoded', False)
        route_coordinates_string = paths[0].get('points', '')

        if points_encoded:
            # Decode the points string using polyline algorithm
            decoded_coordinates = polyline.decode(route_coordinates_string)
            #decoded_coordinates = [(round(lat, 7), round(lng, 7)) for lat, lng in decoded_coordinates]
            print('decoded coordinates',decoded_coordinates)
            print('offset destination',offset_destination)
            # Loop through the decoded coordinates
            for i in range(len(decoded_coordinates) - 1):
                lat1, lng1 = decoded_coordinates[i]
                lat2, lng2 = decoded_coordinates[i + 1]
                # Calculate the coordinates along the line segment between (lat1, lng1) and (lat2, lng2)
                interpolated_lat = lat1 + (offset_destination['lat'] - lat1) * (lng2 - lng1) / (lng2 - lng1)
                interpolated_lng = lng1 + (offset_destination['lng'] - lng1) * (lat2 - lat1) / (lat2 - lat1)
                lat_diff = abs(interpolated_lat - offset_destination['lat'])
                lng_diff = abs(interpolated_lng - offset_destination['lng'])
                threshold = 0.00001

                if lat_diff < threshold and lng_diff < threshold:
                    # Destination coordinate closely matches a point along the route
                    return JsonResponse(routing_data)
                print('asd' ,lng_diff , offset_destination['lng'])

            # If loop completes without finding a match, return an error response
            return JsonResponse({'error': 'No matching route coordinates found.'}, status=404)
        #return JsonResponse(routing_data)
        return JsonResponse({'error': 'Error connecting to GraphHopper API.'}, status=500)
    return JsonResponse({'error': 'Invalid HTTP method.'}, status=405)

As an example you can’t expect the route to match your routing points: Example

1 Like

yeah i got the solution, thanks for the assist though.