2013-03-15 69 views
0

我的Google地圖存在一些問題。我知道問題是關於循環,並希望有更好的方式來解決問題的一些信息Google地圖標記工具提示無法正常工作,mvc 4

因此,讓我爲你畫一幅畫;我有一個地圖顯示位置通過緯度/經度(從數據庫拉)。這些標記有一個附加到他們的addlistener,允許你點擊它們來顯示信息,問題是,當我點擊任何標記時,工具提示將關注添加到地圖上的最後一個項目,並顯示標記的信息。這很可笑! (不是說唱歌手)

我想得到一把錘子,把我的地圖重新塑造成形,而不是在你們明智的建議之前。以下是密碼。

function initialize() { 
     var mapOptions = { 
      center: new google.maps.LatLng([REMOVED], [REMOVED]), 
      zoom: 11, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     var map = new google.maps.Map(document.getElementById("map-canvas"), 
      mapOptions); 
     // RAZOR BEGIN 

     @foreach (var item in Model) { 
<text> 
     var markerlatLng = new google.maps.LatLng(@(item.latitude), @(item.longitude)); 
     var title = '@(item.address1)'; 
     var description = '@(item.averageRating)'; 
     var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>' 

     var infowindow = new google.maps.InfoWindow({ 
      content: contentString 
     }); 

     var marker = new google.maps.Marker({ 
      position: markerlatLng, 
      title: title, 
      map: map, 
      draggable: false 
     }); 

     google.maps.event.addListener(marker, 'click', function() { 
      map.setZoom(15); 
      map.setCenter(marker.getPosition()); 
      //open a div on the mouse location? 
      infowindow.open(map, marker); 
     }); 

     </text> 
    }  
     //RAZOR END 

正如您所看到的,它會循環瀏覽模型並獲取相關信息以放置在地圖上。

我試過把剃鬚刀循環之外的聽衆放在外面,但這只是讓它不能工作。

一如既往,Stackoverflow,你的幫助將是非常,非常感謝。

PS。這次沒有Cookie。

回答

1

我想你對Razor/JS如何一起工作感到困惑。

請記住,Razor在服務器端執行,JavaScript在客戶端執行,如果您在加載頁面後進入頁面並查看源代碼,您將看到您的問題。您基本上爲模型中的每個元素生成大部分JavaScript代碼,這意味着每個變量都會被聲明多次。

我會做什麼(不知道這是否是最好的方法)是這樣的:

<text> 
// these are javascript arrays 
var locations = []; 
var descriptions = []; 
</text> 

@* This is the razor loop *@ 
@foreach (var item in Model) { 
    <text> 
    locations.push(google.maps.LatLng(@(item.latitude), @(item.longitude))); 
    descriptions.push('<h3>@(item.address1)</h3><p>@(item.averageRating)</p>'); 
    </text> 
} 

// Now using javascript, create a loop that will create the markers and assign the listeners 
<text> 
for(var i : locations){ 

    var infowindow = new google.maps.InfoWindow({ 
     content: descriptions[i]; 
    }); 

    var marker = new google.maps.Marker({ 
     position: locations[i], 
     title: title, 
     map: map, 
     draggable: false 
    }); 

    google.maps.event.addListener(marker, 'click', function() { 
     map.setZoom(15); 
     map.setCenter(marker.getPosition()); 
     //open a div on the mouse location? 
     infowindow.open(map, marker); 
    }); 
} 
</text> 

另一種選擇是在你的剃鬚刀代碼使用JSON序列,讓你打印整個模型一個JSON字符串,然後在javascript中解析,而不是手動構建數組。

請注意,我沒有測試這個代碼,所以可能會出現一些錯誤,但這個想法是讓你走上正軌。

希望這會有所幫助。

+0

謝謝,這對我有意義!我會給這個lookie。 – Jay 2013-03-15 16:33:49