2016-09-17 144 views
0

我有一個列表,其中包含我作爲對象傳遞給我的視圖的客戶端的名稱,緯度和長度。谷歌地圖地址列表爲Javascript

在這個相同的視圖中,我有一個JavaScript代碼來生成帶有標記的Google Map,使用客戶端lat long。

我不熟悉開發,我不知道這是否是最好的方式,但我的問題是:我怎麼能得到這個列表內我的JavaScript加載標記?

控制器:

public ActionResult Index() 
    { 
     List<object> ec = new List<object>(); 
     ec.Add(db.Estoques.ToList()); 
     ec.Add(db.Clientes.ToList()); 
     return View(ec); 
    } 

查看:

@model IEnumerable<object> 

@{ 
    List<selectgas.ADOs.ADOClientes> ListaClientes = Model.ToList()[1] as List<selectgas.ADOs.ADOClientes>; 
} 

<div id="map_wrapper"> 
    <script async defer 
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCxevnGqIeXmmR_rZx6-aLMHFS6gZ2O3qs&callback=initialize"> 
    </script> 
    <script type="text/javascript"> 

     $(document).ready(function() { 
      // execute 
      (function() { 
       // map options 
       var options = { 
        zoom: 5, 
        center: new google.maps.LatLng(39.909736, -98.522109), // centered US 
        mapTypeId: google.maps.MapTypeId.TERRAIN, 
        mapTypeControl: false 
       }; 

       // init map 
       var map = new google.maps.Map(document.getElementById('map_canvas'), options); 

       // NY and CA sample Lat/Lng 
       var southWest = new google.maps.LatLng(40.744656, -74.005966); 
       var northEast = new google.maps.LatLng(34.052234, -118.243685); 
       var lngSpan = northEast.lng() - southWest.lng(); 
       var latSpan = northEast.lat() - southWest.lat(); 

       // set multiple marker 
       for (var i = 0; i < ListaClientes.lenght; i++) { 
        // init markers 
        var marker = new google.maps.Marker({ 
         position: new google.maps.LatLng(ListaClientes[i].Lat, ListaClientes[i].Long), 
         map: map, 
         title: 'Click Me ' + i 
        }); 

        // process multiple info windows 
        (function(marker, i) { 
         // add click event 
         google.maps.event.addListener(marker, 'click', function() { 
          infowindow = new google.maps.InfoWindow({ 
           content: 'Hello, World!!' 
          }); 
          infowindow.open(map, marker); 
         }); 
        })(marker, i); 
       } 
      })(); 
     }); 


    </script> 
    <div id="map_canvas" class="mapping"></div> 
</div> 

回答

0

假設控制器返回以下集合:

public ActionResult Index() 
{ 
    var cities = new List<City>(); 
    cities.Add(new City() { Title = "Paris", Lat = 48.855901, Lng = 2.349272}); 
    cities.Add(new City() { Title = "Berlin", Lat = 52.520413, Lng = 13.402794 }); 
    cities.Add(new City() { Title = "Rome", Lat = 41.907074, Lng = 12.498474 }); 
    return View(cities); 
} 

其中

public class City 
{ 
    public string Title { get; set; } 

    public double Lat { get; set; } 

    public double Lng { get; set; } 
} 

然後JavaScript數組可以初始化這樣的:

var cities = @Html.Raw(Json.Encode(Model)); 

Demo

+1

謝謝!有用! –