简体   繁体   English

如何从Google地图获取当前的经度和纬度

[英]How to get current latitude and longitude from Google map

I have some problem to get lat/lng from google map in my application. 我在应用程序中从Google地图获取经/纬度时遇到问题。
When I put in alert message 'lat()' or 'lng()' map is not rendered at all. 当我输入警报消息“ lat()”或“ lng()”时,地图根本不会呈现。
In the code that I put bellow on map click I get alert with 'undefined' message. 在我将波纹管放在地图上的代码中,单击“未定义”消息会提醒我。
I want to store lat and lng in text field on page when user move map (here I try with click) but something doesn't work here? 我想在用户移动地图时在页面上的文本字段中存储经纬度(Lat)和lng(在这里我尝试单击),但是这里不起作用?

function initialize() {
        var latlng = new google.maps.LatLng(44.012, 20.921);
        var myOptions = {
            zoom: 13,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        google.maps.event.addListener(map, "click", function (latlng) {
            if (latlng) {
                alert(latlng.lat);
            }
        });
    }

latlng should be in the event object passed in. So, in order to extract it, you would do something like this: latlng应该在传入的event对象中。因此,为了提取它,您可以执行以下操作:

google.maps.event.addDomListener(map, 'click', function(event) {
    var myLatLng = event.latLng;
    var lat = myLatLng.lat();
    var lng = myLatLng.lng();
    alert( 'lat '+ lat + ' lng ' + lng ); 

}

You can also get lat and lng by the instance of google map: 您还可以得到latlng的谷歌地图的实例:

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); // map instance

google.maps.event.addListener(map, "click", function () {
    var lat = map.data.map.center.lat();
    var lng = map.data.map.center.lng();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM