Retrieve latitude and longitude of a draggable pin via Google Maps API V3

后端 未结 8 469
礼貌的吻别
礼貌的吻别 2020-11-29 18:23

I will explain. I managed to have a draggable pin on a map. I want to retrieve the coordinates of this point and put them into two fields: Latitude and Longitude. These coor

相关标签:
8条回答
  • 2020-11-29 19:08
        var zoomLevel = map.getZoom();
        var pos = (event.latLng).toString();
    
        $('#position').val(zoomLevel+','+pos); //set value to some input
    

    Example Run JsFiddle

    0 讨论(0)
  • 2020-11-29 19:09
    google.maps.event.addListener(marker, 'dragend', function (event) {
        document.getElementById("latbox").value = this.getPosition().lat();
        document.getElementById("lngbox").value = this.getPosition().lng();
    }); 
    

    worked well for me.. Thanks..

    0 讨论(0)
  • 2020-11-29 19:11

    Look at the official code sample from Google Maps API reference: http://gmaps-samples-v3.googlecode.com/svn/trunk/draggable-markers/draggable-markers.html

    0 讨论(0)
  • 2020-11-29 19:12

    The code that is actually working is the following:

    google.maps.event.addListener(marker, 'drag', function(event){
           document.getElementById("latbox").value = event.latLng.lat();
           document.getElementById("lngbox").value = event.latLng.lng();
    });
    

    It would be better if the map could be re-centered once the pin is dropped. I guess it can be done with map.setCenter() but I'm not sure where I should put it. I tried to put it right before and right after this piece of code but it won't work.

    0 讨论(0)
  • 2020-11-29 19:14

    Check this fiddle

    In the following code replace dragend with the event you want. In your case 'click'

    google.maps.event.addListener(marker, 'dragend', function (event) {
        document.getElementById("defaultLatitude").value = event.latLng.lat();
        document.getElementById("defaultLongitude").value = event.latLng.lng();
    });
    
    0 讨论(0)
  • 2020-11-29 19:20

    Either of these work

    google.maps.event.addListener(marker, 'click', function (event) {
        document.getElementById("latbox").value = event.latLng.lat();
        document.getElementById("lngbox").value = event.latLng.lng();
    });
    
    google.maps.event.addListener(marker, 'click', function (event) {
        document.getElementById("latbox").value = this.getPosition().lat();
        document.getElementById("lngbox").value = this.getPosition().lng();
    });
    

    You might also consider using the dragend event also

    google.maps.event.addListener(marker, 'dragend', function (event) {
        document.getElementById("latbox").value = this.getPosition().lat();
        document.getElementById("lngbox").value = this.getPosition().lng();
    });
    
    0 讨论(0)
提交回复
热议问题