Quantcast
Channel: Question and Answer » json
Viewing all articles
Browse latest Browse all 148

How can I load GeoJSON from URL to leaflet? [closed]

$
0
0

I want to use leaflet’s L.GeoJSON to load the GeoJSON from my URL. I have tested to use leaflet-ajax plugin and it worked.

The codes as follow:

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<script src="dist/leaflet-ajax/leaflet-ajax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  function onEachFeature_SG(feature, layer) {
      if (feature.properties && feature.PLN_AREA_N) {
          layer.bindPopup(feature.properties.PLN_AREA_N);
      }
  }

  var geojsonLayer = new L.geoJson().addTo(map);
  var popup = new L.popup();

  $.ajax({
  dataType: "json",
  url: "mygeojsonurl",
  success: function(data) {
      $(data.features).each(function(key, data) {
          console.log(data.properties.PLN_AREA_N); //has data

              var centerLat = data.properties.cent_lat;
              var centerLon = data.properties.cent_lon;
              var centLatLon = new L.LatLng(centerLat, centerLon); //this is used to place the popup in the "mouseover" function
              layer.setStyle(default_style);

              if (data.properties && data.properties.popupContent) {
                  layer.bindPopup(data.properties.PLN_AREA_N);
              }

              layer.on('click', function (e) {
                console.log(e);
                e.setContent(data.properties.PLN_AREA_N);
                e.openPopup(popup);
              })

              layer.on('mouseover', function (e) {
                  console.log(e);
                  layer.setStyle(default_style);
                  layer.openPopup(centLatLon);
              });
              layer.on('mouseout', function (e) { console.log(e); layer.setStyle(default_style) });
          }

          geojsonLayer.addData(data);
      });
  }
}).error(function() {});

I want it to be simple by using Leaflet directly.


Viewing all articles
Browse latest Browse all 148

Trending Articles