当从HTML5 Geolocation提供LatLng线时,Google maps API会显示空白地图

时间:2013-08-08 02:40:53

标签: javascript html5 google-maps google-maps-api-3

我正在尝试使用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);

1 个答案:

答案 0 :(得分:2)

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

center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),