アプリ全体で Google マップを使用している MVC アプリケーションがあります。簡単にするために、マップを初期化し、マップ表示を設定する JavaScript ファイルを作成しました。
私のアプリケーションでは、フロント エンドの開発者が単純な JavaScript 呼び出しで地図の位置の中心を変更できるようにしたいと考えています。残念ながら、マップを宣言してアプリケーションをロードした後、JavaScript コールバックをマップ変数に行おうとすると、マップ JS 変数 (およびすべての変数) が null になります。これにより、インスタンスがマップにドロップされ、場所を変更できなくなります (私は信じています)。
以下の 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();
}