Panning / Moving Leaflet map to new location based on updated coordinates / click

51 Views Asked by At

I am so close on this but my poor Javascript is letting me down.

I'm stuck on adding an event listener addListener() or on() to a Leaflet map to move the map.

On my non profit ancient sites web site I have a page where you can look up and jump to a location based on a town name lookup. Here is the old version with Google maps which I am trying to update: https://www.megalithic.co.uk/searchtown.php Search on the name of a town (for example Cheddar), click on the name to show the location on a map, and click again on a different town name to move the map to the new location.

Here is the new Leaflet version. The code is working apart from when you click to move an existing map to a different location. Uploaded here: https://www.megalithic.co.uk/searchtown-leaflet.php

A couple of examples I've been following: Moving the view area when a button is clicked and https://groups.google.com/g/leaflet-js/c/Q9XUc7ArJeI?pli=1

Many thanks for your help

my code:

echo "
<script type=\"text/javascript\">

// this function will be called by our JSON callback
// the parameter jData will contain an array with geonames objects
function getLocation(jData) {
  if (jData == null) {
    // There was a problem parsing search results
    return;
  }

  var html = '';
  var geonames = jData.geonames;
  for (i=0;i< geonames.length;i++) {
     var name = geonames[i];
     // we create a simple html list with the geonames objects
     // the link will call the center() javascript method with lat/lng as parameter
     html = html + '<a href=\"javascript:center(' + name.lat +',' + name.lng + ');\">' + name.name + '</a><br><br>';
  }
  document.getElementById('resultDiv').innerHTML = html;
}

function center(lat,lng){
  if (map instanceof L.map) {
        map.panTo([lat, lng], 2);
        //map.setView([lat, lng], 13); // alternative from https://groups.google.com/g/leaflet-js/c/Q9XUc7ArJeI?pli=1
    } else {
    var map = L.map('map').setView([lat, lng], 13);
    var tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a>'
    }).addTo(map);
    }
    var latitude = document.getElementById(\"latitude\");
    var longitude = document.getElementById(\"longitude\");
    latitude.value = lat;
    longitude.value = lng;
    L.DomEvent.addListener (map, \"click\", function (e) {
       latitude.value  = e.latLng.lat().toFixed(6)
       longitude.value = e.latLng.lng().toFixed(6);
    });

}

// previous version of function that worked on Google Maps
function center_old_google(lat,lng){
        var myOptions = {
          center: new google.maps.LatLng(lat,lng),
          zoom: 10,
          scaleControl: true,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById(\"goomap\"),
            myOptions);
  var latitude = document.getElementById(\"latitude\");
  var longitude = document.getElementById(\"longitude\");
  latitude.value = lat;
  longitude.value = lng;
google.maps.event.addListener(map, \"click\", function (e) {
       latitude.value  = e.latLng.lat().toFixed(6)
       longitude.value = e.latLng.lng().toFixed(6);
    });
}

// TO DO CONVERT THIS FROM GOOGLE TO LEAFLET
//google.maps.event.addListener(map, \"click\", function (e) {
//       latitude.value  = e.latLng.lat().toFixed(6)
//       longitude.value = e.latLng.lng().toFixed(6);
//});

// from example here: https://stackoverflow.com/questions/35575428/moving-the-view-area-when-a-button-is-clicked
//map.addListener(map, \"click\", function (e) {
//    center(lat,lng)
//});

// calls the geonames JSON webservice with the search term
function search() {
  request = 'https://secure.geonames.org/searchJSON?q=' +  encodeURIComponent(document.getElementById('q').value)  + '&maxRows=10&callback=getLocation&username=mega';

  // Create a new script object
  // Build the script tag
  aObj.buildScriptTag();
  // Execute (add) the script tag
  aObj.addScriptTag();
}

</script>
<script src=\"https://unpkg.com/[email protected]/dist/leaflet.js\"></script>
";
1

There are 1 best solutions below

0
a_deeee On

Check your console log. It says:

Map.js:1105 Uncaught Error: Map container is already initialized.
at i._initContainer (Map.js:1105:10)
at i.initialize (Map.js:136:8)
at new i (Class.js:22:20)
at t.map (Map.js:1728:9)
at center (searchtown-leaflet.php:277:17)
at <anonymous>:1:1

Remove previous map element before you try to reload the map.

if (map != undefined) { map.remove(); } 

for more details