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) {

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

  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

              if (data.properties && data.properties.popupContent) {

              layer.on('click', function (e) {

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

}).error(function() {});

I want it to be simple by using Leaflet directly.

  • Do you load your js-code example with an extra file or did you just forgot the <script></script> tags? – wittich Feb 19 '16 at 7:45
  • Do you need to do this asynchronously (on click of a button) or only once at page load? – til_b Feb 19 '16 at 8:17
  • 1
    I'm having trouble understanding your question. Why do you not want to use leaflet-ajax ? What is going wrong with what you have tried? Where are you currently stuck? The question in its current state cannot be answered. – Devdatta Tengshe Feb 19 '16 at 9:10

Plain leaflet does not offer asynchronous loading from external resources.

If you really want to craft all this youself, you could use the plain XMLHTTPRequest http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp object and craft all the functionality you need with it.

But I think it would be useless. Just include jquery and have all the functionality available. Or give specific reasons on why you do not want more librarys.

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