javascript - 通过 Javascript 重置 Google map 中的 map 中心

标签 javascript google-maps

我有一个 MVC 应用程序,它在整个应用程序中使用 Google map 。为了简单起见,我创建了一个 JavaScript 文件来初始化 map 并设置 map 显示。

在我的应用程序中,我希望允许前端开发人员通过简单的 JavaScript 调用来更改 map 位置的中心。不幸的是,在声明 map 并加载应用程序后,如果您尝试对 map 变量进行 JavaScript 回调,则 map JS 变量(和所有变量)将为 null。这会将实例放置到 map 上,并且不允许我更改位置(我相信)。

在下面的 JS 代码中,我尝试从 HTML 页面调用 setLocation 来重置位置。这是代码的失败部分。感谢帮助。

var map;
var geocoder;
var marker;

$(document).ready(function () {
    initialize();
    $(function () {
        $("#address").autocomplete({
            //This bit uses the geocoder to fetch address values
            source: function (request, response) {
                geocoder.geocode({ 'address': request.term }, function (results, status) {
                    response($.map(results, function (item) {
                        return {
                            label: item.formatted_address,
                            value: item.formatted_address,
                            latitude: item.geometry.location.lat(),
                            longitude: item.geometry.location.lng()
                        }
                    }));
                })
            },

            select: function (event, ui) {
                $("#Place_Latitude").val(ui.item.latitude);
                $("#Place_Longitude").val(ui.item.longitude);
                var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
                marker.setPosition(location);
                map.setCenter(location);
            }
        });
    });
});

function setLocation(lat, lon) {
    var location = new google.maps.LatLng(lat, lon);
    marker.setPosition(location);
    map.setCenter(location);
}
function initialize() {
    var location = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        center: location, zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    marker = new google.maps.Marker({
        map: map,
        draggable: true
    });
    marker.setPosition(location);

    geocoder = new google.maps.Geocoder();
}

最佳答案

这看起来很糟糕:

return {
       label: item.formatted_address,
       value: item.formatted_address,
       latitude: item.geometry.location.lat(),
       longitude: item.geometry.location.lng()
       }

地理编码器是异步的,无法从回调例程返回任何内容。您需要使用回调中的变量。

关于javascript - 通过 Javascript 重置 Google map 中的 map 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13709570/

相关文章:

php - 使用正则表达式过滤固定长度为0或4位的年份

javascript - 将谷歌地图上的标记从一个地方平滑地移动到另一个地方

带有多个标记的javascript googlemaps在使用cordova应用程序的android中不显示标记

java - 从 mysql db 在 android map 上显示点

javascript - 为什么没有定义组件

javascript - 如何在单击时交替使用 jquery 切换滑动操作

javascript - 如何在不离开当前页面的情况下创建点击调用按钮?

java - 在 Android 应用程序的 MapView 中添加指南针校准选项

javascript - Google map API V3 和 Internet Explorer

javascript - 在页面上运行 JavaScript 代码而不显示浏览器窗口