0

I have been trying for the past hour to take the coordinates of the map edge in a OSM/leaflet application I am making. While I can get the coordinates of the center, and I can get the coordinates of the two poinths the user inputs, the bounds of the map remain unchanging and static on the ones the map loaded. I think it has to do with the map.setView() I call in the start of the code, but I am not sure how to fix that. The code is as follows (the problematic part is actually on the lower part of the code):

var map = L.map('map').setView([37.92,23.69], 13);
var bounds=map.getBounds();
var nodeArray=new Array();
var markerArray = new Array();
var startPoint=null;
var endPoint=null;
var lowerBounds=bounds.getSouthWest();
var upperBounds=bounds.getNorthEast();
var markerCounter=0;



L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
maxZoom: 18}).addTo(map);

var popup = L.popup();
var road = L.polyline(nodeArray).addTo(map);

map.on('click', onMapClick);
function onMapClick(e) {
    markerCounter=markerArray.length;
    if (markerCounter==2){
        map.removeLayer(markerArray[0]);
        map.removeLayer(markerArray[1]);
        markerArray=new Array();
        endPoint=null;
        startPoint=null;
    }else{
        var marker = new L.Marker(e.latlng, {draggable:false});
        markerArray.push(marker);
        for (i=0;i<=markerArray.length;i++){
            map.addLayer(marker);
        }
        if (markerCounter==1){
            marker.bindPopup("Your destination is: "+(e.latlng.toString()).substr(6,20)).openPopup();
            endPoint=(e.latlng.toString()).substr(6,20);
            markerCounter=2;
        }
        if (markerCounter==0){
            marker.bindPopup("Your starting place is: "+(e.latlng.toString()).substr(6,20)).openPopup();
            startPoint=(e.latlng.toString()).substr(6,20);
            markerCounter=1;
        }

    }
};

function runScript(){
    if (markerCounter==0){
        alert('You have give us no data. We cannot calculate a route');
    }else if (markerCounter==1){
        alert('You have give us only one point. We cannot calculate a route');
    }else{
        console.log('LB:'+lowerBounds+" - "+"UB:"+upperBounds+"/SP:"+startPoint+" - EP:"+endPoint);
        } 
}

Does anyone have any idea what is the problem?I am unfortunately entirely new to JS and OSM/Leaflet, so I cannot really see easily problems like those.

2
  • 1
    I don't see you using map.getBounds() anywhere after the map is initilized. You are using var bounds=map.getBounds(); only once. And that is before you fully initilize the map. Commented Jun 10, 2013 at 9:06
  • Thanks! I forgot to add the code before I request the lower/upper bounds.
    – Spyros
    Commented Jun 10, 2013 at 9:09

2 Answers 2

1

You must update your variable bounds every time you want to access the current bounds of the map. In your code, this would look like this:

function runScript() {
  ...
  else {
    bounds = map.getBounds()
    lowerBounds = bounds.getSouthWest()
    upperBounds = bounds.getNorthEast()
    console.log('LB:'+lowerBounds+" - "+"UB:"+upperBounds+"/SP:"+startPoint+" - EP:"+endPoint)
  }
}

Alternatively you could bind a listener to the map that fires on moveend:

map.on("moveend", (e) => { 
    // updates always after map has been moved 
    bounds = map.getBounds()
    lowerBounds = bounds.getSouthWest()
    upperBounds = bounds.getNorthEast()
})
-1

This is easy

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Map</title>
    <link
      rel="stylesheet"
      href="https://unpkg.com/[email protected]/dist/leaflet.css"
      integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
      crossorigin=""
    />
    <script
      src="https://unpkg.com/[email protected]/dist/leaflet.js"
      integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
      crossorigin=""
    ></script>
    <style>
      #map {
        width: 1000px;
        height: 1000px;
        margin: auto;
        border: 30px solid rgb(119, 26, 26);
        padding: 2px;
        align-content: center;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map = L.map("map").setView(
        [10.04632855165017, 105.76787283733059],
        18
      );

      L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
        attribution:
          '&co642py; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
      }).addTo(map);

      var polylines = [];
      var startPoint = null;
      var endPoint = null;

      map.on("click", function (e) {
        if (!startPoint) {
          startPoint = e.latlng;
          L.marker(startPoint).addTo(map);
        } else {
          endPoint = e.latlng;
          L.marker(endPoint).addTo(map);
          var newPolyline = L.polyline([startPoint, endPoint], {
            color: "red",
          }).addTo(map);
          polylines.push(newPolyline);

          var distance = startPoint.distanceTo(endPoint).toFixed(2);
          var popup = L.popup()
            .setLatLng(endPoint)
            .setContent("distance = " + (distance / 1000).toFixed(2) + "km")
            .openOn(map);

          startPoint = null;
          endPoint = null;
        }
      });
    </script>
  </body>
</html>
1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented May 9 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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