0

I inserted a map on my webpage by using the Leaflet library. What I want to do is to show a map zoomed on a specific region according to which city the user types into a text field.

I firstly initialized my map on my JS file:

function initMaps(){

    map = L.map('leaflet').setView([0, 0], 13);

    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
        'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
    }).addTo(map);

}

My javascript code also has an Ajax call. What I want to do now is to reset the coordinates on the Ajax call. I wrote the following:

var readCoordinates = function(){

    $.ajax({
        url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "+Italy&format=geocodejson",
        dataType: "json",
        success: function (data) {

            setTimeout(function () {

                for (let i = 0; i < data.features.length; i++) {
                    let coordinate = data.features[i].geometry.coordinates;   

                    console.log(coordinate);

                    map.setView(coordinate, 13);

                    console.log("ajax and for loop have been activated");
                    console.log(coordinate.geometry.coordinates);
                };
                $("#ristoranti").prop("disabled", false);

            }, 1000);
        }
    });

};

The API I'm referring to in the URL is the following: https://nominatim.openstreetmap.org/search?q=Roma%20Italy&format=geocodejson

What I did is trying to reset the coordinates here: map.setView(coordinate, 13);

after having cycled the elements in the JSON object, see the following:

for (let i = 0; i < data.features.length; i++) {
                    let coordinate = data.features[i].geometry.coordinates;

I may display several coordinates in the console, see the following:

Too many coordinates

That's because in the JSON file I get through the API request there are several:

enter image description here

The result of this is the following map, which isn't zoomed anywhere:

resulting map

Which coordinates should I take in order to display that specific region?

      • EDIT - - -

I changed the code because I'm trying to get a specific subobject, i.e. the one in the screen below (which has "type" = "city"):

subobject of the JSON file in the API request

The new snippet is the one below, where I add an if statement:

var readCoordinates = function(){

    $.ajax({
        url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "+Italy&format=geocodejson",
        dataType: "json",
        success: function (data) {

            setTimeout(function() {

                for (let i = 0; i < data.features.length; i++) {

                    debugger;    

                    let type = data.features[i].properties.geocoding.type;

                    if(  $(type).val() === "city") {

                    let coordinate = data.features[i].geometry.coordinates;

                    let lng = coordinate[0];

                    let lat = coordinate[1];

                      map.setView([lng, lat], 13);

                    console.log("ajax and for loop have been activated");
                    console.log(coordinate);}
                };

                $("#ristoranti").prop("disabled", false);

            }, 1000);
        }
    });

};

I'm doing the debugger and get many undefined values:

type is undefined feature is not defined properties is not defined geocoding is not defined type is undefined

2 Answers 2

1

I would do something like that:

if (typeof data.features[0] !== 'undefined') {
    let coordinate = data.features[0].geometry.coordinates;
    var latlng = L.latLng(coordinate.reverse());
    map.flyTo(latlng, 12)
}
  1. Be sure to have something in your array
  2. Get data from the first item since it should be the correct one in most case
  3. Create a latlng with those coordinates. Be careful, sometime you need to reverse the array to have the correct position.
  4. Use flyTo to have a smooth transition to your coordinates. 12 is the zoom level

You don't need to loop over the data since you need only one position. You can replace the for with that.

1

You're having two problems here:

Not the answer you're looking for? Browse other questions tagged or ask your own question.