Uncaught TypeError: Cannot read lat property with undefined when serializing leaf data using $ .param ()

I would like a preface to this: I am very new to JavaScript. I am trying to position a userโ€™s location and map borders using Leaflet and AJAX call. In the stateUpdater.onLocationFound event handler, the stateUpdater.onLocationFound operators print the correct user coordinates and map borders, however I get Uncaught TypeError: Cannot read property 'lat' of undefined when I try to serialize these values โ€‹โ€‹using $.param() . I am using Leaflet v0.7.2 and jQuery 1.11.0.

 var map; $(document).ready(function() { map = new L.map('map').setView([41.52, -71.09], 11); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18 }).addTo(map); map.on('locationfound', stateUpdater.onLocationFound); stateUpdater.poll(); }); var stateUpdater = { errorSleepTime: 10000, poll: function() { map.locate({setView: true, maxZoom: 18}); }, onLocationFound: function(e) { //This log statement produces the correct output console.log(e.latlng.toString()); var bounds = map.getBounds(); //As does this one console.log(bounds.toBBoxString()) var args = { "map_ne": bounds.getNorthEast(), "map_sw": bounds.getSouthWest(), "user_coords": e.latLng }; //Uncaught TypeError thrown here $.ajax({url: "/a/state/updates", type: "POST", dataType: "text", data: $.param(args), success: stateUpdater.onSuccess, error: stateUpdater.onError}); }, onSuccess: function(response) { console.log(response); stateUpdater.errorSleepTime = 10000; window.setTimeout(stateUpdater.poll, 10000); }, onError: function(response) { stateUpdater.errorSleepTime *= 2; console.log("Poll error; sleeping for", stateUpdater.errorSleepTime, "ms"); window.setTimeout(stateUpdater.poll, stateUpdater.errorSleepTime); }, }; 

I no longer have any idea what might be causing this, so I will be very grateful for the help.

+6
source share
1 answer

It seems that bounds.getNorthEast () , bounds.getSouthWest () and e.latlng return objects that additionally contain some functions to lat, lng , like equal () and toString () , which prevents $. param () serializing your data correctly and this causes your error, here is a good way to get only what you need from these objects:

  var ll= $.extend({},{lat:e.latlng.lat, lng:e.latlng.lng}), neBounds = bounds.getNorthEast(), neBoundsLl = $.extend({},{lat:neBounds.lat, lng:neBounds.lng}), swBounds = bounds.getSouthWest(), swBoundsLl = $.extend({},{lat:swBounds.lat, lng:swBounds.lng}), args = { "map_ne": neBoundsLl, "map_sw": swBoundsLl, "user_coords": ll }; 

I tested this code and it worked for me, the error went away and the ajax request was sent successfully.

+5
source

All Articles