0

I am quite new to both javascript and php.
However, I am making a website with a leaflet map letting users find pubs in a certain area.
I created a funciton called draw(), which is called when pressing the submit button after entering a text string in the search box. Here is the function:

if (map.hasLayer(postGroup)) {
    postGroup.clearLayers();
}
if (map.hasLayer(pubGroup)) {
    pubGroup.clearLayers();
}


 sokverdi=document.getElementById("search").value

$.getJSON('http://localhost/user/postcoderetr.php?search=' + sokverdi,
function(data) {
    L.geoJson(data, {
    style: function(feature) {
        str=document.getElementById("search").value;
        if (feature.properties.label==str) {
            return {color: "#ff0000", weight:1, opacity: 0.7};
            } else {
            return {color: "#33AFFF", weight:1, opacity: 0.4};
            }
        }}).addTo(postGroup);
});
  $.getJSON('http://localhost/user/pubinpostcode.php?search=' + sokverdi,
function(data) {
    L.geoJson(data, {
    pointToLayer: function (feature, latlng) {
      return L.circleMarker(latlng, markerOptions);
    }}).addTo(pubGroup);
})
;

$.getJSON('http://localhost/user/pubnamesearch.php?search=' + sokverdi,
function(data) {
    L.geoJson(data, {
    pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, markerOptions)}
    }).addTo(pubGroup);
})};

The question is: How do I either pan to or zoom to the layer that has been retrieved from the databse via the PHP script in the $.getJSON method?
I would like Leaflet to pan to the features drawn in the map, no matter which PHP request they are coming from. Should the panning be done inside this function, or outside?

0

panTo needs a L.latLng, so for the first function (assuming this returns a poly):

var layer = L.geoJson(data, {
style: function(feature) {
    str=document.getElementById("search").value;
    if (feature.properties.label==str) {
        return {color: "#ff0000", weight:1, opacity: 0.7};
        } else {
        return {color: "#33AFFF", weight:1, opacity: 0.4};
        }
    }});    
map.panTo(layer.getBounds().getCenter());
layer.addTo(postGroup);

and something like this for the second and third:

L.geoJson(data, {
    pointToLayer: function (feature, latlng) {
      map.panTo(latlng);
      return L.circleMarker(latlng, markerOptions);
    }});

Seems easiest to call panTo inside the functions. Also that way you are not trying to pan to invalid response data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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