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

19

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

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

谢谢您

5个回答

36

试一下这个 :)

    <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>

8
使用google.loader.ClientLocation不是一个好主意,参见https://dev59.com/oWYq5IYBdhLWcg3wzDhI。 - user1565007

13

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

从CDN中包含相关脚本:

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

HTML

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

CSS

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

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/


它运行良好,但不够准确,存在约200米的误差。我们如何使其更精确? - Rohitashv Singhal

7

3

1

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

google.loader.ClientLocation.address.city

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接