我有一个 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/