Search code examples
javascriptjqueryajaxgraphhopper

How to make an AJAX call to GraphHopper Matrix API


I need to send this json with the following information, but at the time of making the request I get an error

message: "Unsupported content type application/x-www-form-urlencoded; charset=UTF-8"
status: "finished"

I don't the correct way to the request

request sent for JS and Jquery:

<script>
    $("#request").click(() => {

        var url = "https://graphhopper.com/api/1/matrix?key=d5ab0f9f-538a-4842-926a-9667970d4061";
        var data = {
            "elevation": false,
            "from_points": [-33.467482, -70.624736],
            "to_points": [
                [-33.468756, -70.622155],
                [-33.467359, -70.627332],
                [-33.466348, -70.621985]
            ],
            "from_point_hints": ["nuble"],
            "to_point_hints": [
                "place 1",
                "place 2",
                "place 3"
            ],
            "out_arrays": [
                "distances",
                "times"
            ],
            "vehicle": "car"
        };

        $.ajax({
            url: url,
            data: JSON.stringify(data),
            method: 'POST',
            dataType: 'json',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });

    });
</script>

Solution

  • you must first enter the longitude and then the latitude and the next error you had was to specify the head of the ajax request

    the code would be:

    var url = "https://graphhopper.com/api/1/matrix?key=myKey";
            var data ={
        "from_points": [
            [
               -70.6247406,
               -33.4673461
    
            ]
        ],
        "to_points": [
            [
                -70.913138,
                -33.794796,
            ]
        ],
        "from_point_hints": [
            "ñuñoa"
        ],
        "to_point_hints": [
            "places 1"
        ],
        "out_arrays": [
            "times",
            "distances"
        ],
        "vehicle": "car"
    };
    
            $.ajax({
                beforeSend: function(xhrObj) {
                    xhrObj.setRequestHeader("Content-Type", "application/json");
                    xhrObj.setRequestHeader("Accept", "application/json");
                },
                url: url,
                data: JSON.stringify(data),
                type: 'POST', //en este caso
                dataType: 'json',
                success: function(response) {
                    console.log(response);
                },
                error: function(error) {
                    console.log(error);
                }
            });