Javascript 如何使用 Google Maps API v3 获取客户端位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3940767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:44:52  来源:igfitidea点击:

How to get Client location using Google Maps API v3?

javascriptgoogle-maps

提问by manraj82

How do you get Client location using Google Maps API v3? I tried the following code but kept getting the "google.loader.ClientLocation is null or not an object" error. Any ideas why ??

您如何使用 Google Maps API v3 获取客户端位置?我尝试了以下代码,但一直收到“google.loader.ClientLocation 为空或不是对象”错误。任何想法为什么?

if (google.loader.ClientLocation) {
            alert(google.loader.ClientLocation.latitude+" "+google.loader.ClientLocation.longitude);
        }

Thank You

谢谢你

回答by tomodian

Try this :)

尝试这个 :)

    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
    function initialize() {
        var loc = {};
        var geocoder = new google.maps.Geocoder();
        if(google.loader.ClientLocation) {
            loc.lat = google.loader.ClientLocation.latitude;
            loc.lng = google.loader.ClientLocation.longitude;

            var latlng = new google.maps.LatLng(loc.lat, loc.lng);
            geocoder.geocode({'latLng': latlng}, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {
                    alert(results[0]['formatted_address']);
                };
            });
        }
    }

    google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});

    </script>

回答by TrojanMorse

A bit late but I got something similar that I'm busy building and here is the code to get current location - be sure to use local server to test.

有点晚了,但我得到了一些类似的东西,我正在忙着构建,这里是获取当前位置的代码 - 请务必使用本地服务器进行测试。

Include relevant scripts from CDN:

包括来自 CDN 的相关脚本:

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap">

HTML

HTML

<div id="map"></div>

CSS

CSS

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}
#map {
    height: 100%;
}

JS

JS

var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});

// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('Location found.');
        map.setCenter(pos);
    }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
}

DEMO

演示

https://jsfiddle.net/ToreanJoel/4ythpy02/

https://jsfiddle.net/ToreanJoel/4ythpy02/

回答by sren

I couldn't get the above code to work.

我无法让上面的代码工作。

Google does a great explanation though here: http://code.google.com/apis/maps/documentation/javascript/basics.html#DetectingUserLocation

谷歌在这里做了一个很好的解释:http: //code.google.com/apis/maps/documentation/javascript/basics.html#DetectingUserLocation

Where they first use the W3C Geolocation method and then offer the Google.gears fallback method for older browsers.

他们首先使用 W3C 地理定位方法,然后为旧浏览器提供 Google.gears 回退方法。

The example is here:

例子在这里:

http://code.google.com/apis/maps/documentation/javascript/examples/map-geolocation.html

http://code.google.com/apis/maps/documentation/javascript/examples/map-geolocation.html

回答by jmagnusson

No need to do your own implementation. I can recommend using geolocationmarkerfrom google-maps-utility-library-v3.

无需自己执行。我可以推荐使用geolocationmarkerfrom google-maps-utility-library-v3

回答by Kris

It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:

看来您现在不需要反向地理编码,现在直接从 ClientLocation 获取地址:

google.loader.ClientLocation.address.city