2012-12-04 41 views
1

我有一個在整個應用程序中使用Google地圖的MVC應用程序。爲了簡單起見,我創建了一個JavaScript文件來初始化地圖並設置地圖顯示。通過Javascript重置Google地圖中的地圖中心

在我的應用程序中,我希望允許前端開發人員通過簡單的JavaScript調用來更改地圖位置的中心。不幸的是,在聲明地圖並加載應用程序之後,如果您嘗試將JavaScript調用回地圖變量,則地圖JS變量(以及所有變量)爲空。這將實例放到地圖上,並且不讓我改變位置(我相信)。

在下面的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(); 
} 
+0

你有沒有嘗試刪除var地圖;線?似乎你正在設置一個名爲map的新變量,而不是引用你之前設置的變量。 –

回答

0

情況不妙:

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

地址解析器是異步的,不能從回調例程返回任何東西。你需要使用回調中的變量。

0

有什麼你正在嘗試做here一個例子...

看一看theie placeMarker功能以及它們如何初始化地圖...

我的建議是開始用這個例子,並確保工作。如果是這樣,那麼確定實施中的不同之處應該是相對直截了當的。