Why am i not getting exact Longitude when i click

2020-01-29 18:32发布

问题:

In my web app i am trying to fetch longitude and latitude of a marker when i click on it. Following is the code which is setting a marker and then try to get the same marker's latitude and longitude when i click on it:

  var myLatlng = new google.maps.LatLng(55.68322317670628, 13.177157360327598);
  var marker_obj = new google.maps.Marker({
    clickable: true,
    position: myLatlng,
    map: dashboard_map,
    zIndex: i
 });

  marker_obj.setIcon('marker.png');

  google.maps.event.addListener(marker_obj, "click", function(event) {
        var myLatLng = event.latLng;
        var lat1 = myLatLng.lat();
        var lng1 = myLatLng.lng();
        console.log('marker latitude: '+lat1);
        console.log('marker longitude: '+lng1);

        $.ajax({
            type: 'POST',
            url: 'http://localhost:8888/action',
            data: { latitude: lat1, longitude: lng1},
            success: function(result) {
                console.log(result);
            }
        });
    });

When i click on marker i get right latitude but longitude is not same. longitude value is 13.177157360327556, original marker longitude value is 13.177157360327598. Why am i not getting right longitude? Thanks in advance.

回答1:

To get the position of the marker (not the click), use marker_obj.getPosition() not event.latLng.

google.maps.event.addListener(marker_obj, "click", function(event) {
    var myLatLng = marker_obj.getPosition();
    var lat1 = myLatLng.lat();
    var lng1 = myLatLng.lng();
    console.log('marker latitude: '+lat1);
    console.log('marker longitude: '+lng1);

    $.ajax({
        type: 'POST',
        url: 'http://localhost:8888/action',
        data: { latitude: lat1, longitude: lng1},
        success: function(result) {
            console.log(result);
        }
    });
});


回答2:

I would call it a bug.

It's not an issue of the marker or the event, it already happens when you create the LatLng-object.

Try this:

var lat=55.68322317670628,
     lng=13.177157360327598,
     myLatLng = new google.maps.LatLng(lat,lng);

you will see, that lng and myLatLng.lng() have different values.

http://jsfiddle.net/doktormolle/Jm9Ww/

As a workaround I would suggest to use less accurate values with a precision of 6-10 decimals.



回答3:

The "error" is occurring in the constructor for the google.maps.LatLng object.

var latitude = 55.68322317670628;
var longitude = 13.177157360327598;
var myLatlng = new google.maps.LatLng(latitude, longitude);

var longitude_diff = longitude-myLatlng.lng();

The "error" is:

longitude diff: 4.263256414560601e-14 degrees
longitude diff: 2.681678819840079e-9 meters  (2.68 nanometers)

Probably not relevant to anything in the real world that you would use a map for.

example calculation Longitude degrees to meters calculation from this page