0

I am new to Leaflet and I was wondering how to load markers from a database into a leaflet map in php.

I have a php code that gets the latitude and logitude from the database depending on the ward selected and encodes it in json, On the main page I have 3 links namely ward1,ward2,ward3, onclicking the link the different markers wrt that particular ward are loaded on the map accordingly.

How do I call these markers from the json file for each of the wards instead of manually writing it?

 <section>  
      <div id="gmap1"></div>
<ul>
    <li><a id="ward1" href="#">ward1</a></li>
    <li><a id="ward2" href="#">ward2</a></li>
    <li><a id="ward3" href="#">ward3</a></li>
</ul>

      <script>
var lat = 17.9487;
var lng =  73.8919;
var zoom =  10;
var map = new L.Map('gmap1');

var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data &copy; OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 5, maxZoom: 18, attribution: osmAttrib});

map.addLayer(osm);
map.setView(new L.LatLng(lat, lng), zoom);

// add markers
var aa = L.marker(["17.9507900000","73.8886383300"]).bindPopup('AA'),
bb = L.marker([17.9497333300,73.8975800000]).bindPopup('BB'),
cc = L.marker(["17.9507616700","73.8972833300"]).bindPopup('CC'),
dd = L.marker(["17.9468733300","73.8952383300"]).bindPopup('DD'),
ee = L.marker([17.9509700000,73.8885616700]).bindPopup('EE'),
ff = L.marker([17.9503500000,73.8949550000]).bindPopup('FF')


var ward1 = L.layerGroup([aa, bb]);
var ward2 = L.layerGroup([cc, dd]);
var ward3 = L.layerGroup([ee,ff]);

$("#ward1").click(function(event) {
    event.preventDefault();
    if(map.hasLayer(ward1)) {
        $(this).removeClass('selected');
        map.removeLayer(ward1);
    } else {
        map.addLayer(ward1);        
        $(this).addClass('selected');
   }
});

$("#ward2").click(function(event) {
    event.preventDefault();
    if(map.hasLayer(ward2)) {
        $(this).removeClass('selected');
        map.removeLayer(ward2);
    } else {
        map.addLayer(ward2);        
        $(this).addClass('selected');
    }
});

$("#ward3").click(function(event) {
    event.preventDefault();
    if(map.hasLayer(ward3)) {
        $(this).removeClass('selected');
        map.removeLayer(ward3);
    } else {
        map.addLayer(ward3);   

        $(this).addClass('selected');
   }
});

      </script>
</section>
hassan
  • 7,812
  • 2
  • 25
  • 36
random_geek
  • 345
  • 2
  • 8
  • 23

1 Answers1

-1

Have you tried searching on SO? How do you add marker to map using leaflet map.on('click', function) event handler - the same can be applied to when your loading it from a JSON request.

Community
  • 1
  • 1
J. Doe
  • 32
  • 5