0

我正在尝试使用 HTML5 的地理定位功能。我有一个函数来获取坐标,然后另一个函数在调用 Google Maps API 时使用这些坐标。如果我手动指定纬度和经度,效果很好,但由于某种原因它不能以这种方式工作,我只得到一张空地图,控件在那里,但没有实际地图。我相信代码是正确的,但也许我忽略了一些东西。

这是代码:

var x = document.getElementById("msg");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        }
        else { x.innerHTML = "Geolocation is not supported by this browser."; }
    }

    function showPosition(position) {
        var mapOptions = {
            center: new google.maps.LatLng(position.coords.latitude + ", " + position.coords.longitude),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("Map"), mapOptions);
        var acOptions = {
            types: ['establishment']
        };
        var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), acOptions);
        autocomplete.bindTo('bounds', map);
        var infoWindow = new google.maps.InfoWindow();
        var marker = new google.maps.Marker({
            map: map
        });

        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            infoWindow.close();
            var place = autocomplete.getPlace();
            if (place.geometry.viewport) {
                map.fitBounds(place.geometry.viewport);
            } else {
                map.setCenter(place.geometry.location);
                map.setZoom(17);
            }
            marker.setPosition(place.geometry.location);
            infoWindow.setContent('<div><strong>' + place.name + '</strong><br />');
            infoWindow.open(map, marker);
            google.maps.event.addListener(marker, 'click', function (e) {

                infoWindow.open(map, marker);

            });
        });

        var x = document.getElementById("msg");
        x.innerHTML = position.coords.latitude + ", " + position.coords.longitude;
    }

    function showError(error) {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                x.innerHTML = "User denied the request for Geolocation."
                break;
            case error.POSITION_UNAVAILABLE:
                x.innerHTML = "Location information is unavailable."
                break;
            case error.TIMEOUT:
                x.innerHTML = "The request to get user location timed out."
                break;
            case error.UNKNOWN_ERROR:
                x.innerHTML = "An unknown error occurred."
                break;
        }
    }
    google.maps.event.addDomListener(window, 'load', getLocation);
4

1 回答 1

2

LatLng构造函数接受 2 个参数(和一个可选的第三个参数) ,一个纬度和另一个经度都是数字的,而不是作为字符串连接在一起。

center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
于 2013-08-08T02:49:35.367 回答