2012-03-12 79 views
0

我使用MVC模板來允許用戶添加多個地址。他們點擊一個按鈕,這會使用jquery調用我的模板,並且表單將被生成。如果他們想要添加另一個位置,他們再次點擊該按鈕,並設置另一個表單等等。此模板運行正常,但在使用這些模板中的Google地圖時遇到了一些麻煩。如何使用Google地圖的動態表格

在這種情況下使用谷歌地圖的原因是提供一個很好的界面,爲您添加的位置添加經度和緯度。我在這裏使用class而不是id,因爲屏幕上可能有任意數量的地址區域。

在我的MVC的模板,我有以下的標記:

<div class="body"> 
      <div class="st-form-line"> 
       <span class="st-labeltext">Location</span> 
       <a href="#" class="GetPosition">Get Latitude &amp; Longitude positions based on above address details.</a> 
       <div class="mapContainer" style="display:none;"> 
        <p>If the map position is incorrect simply drag the pointer to the correct location.</p> 
        <div class="map" style="width: 450px; height: 350px;"><br/></div> 
       </div> 
       <div class="clear"></div> 
      </div> 

      <div class="st-form-line"> 
       <span class="st-labeltext">@Html.LabelFor(model => model.Address.Longitude)</span> 
       @Html.EditorFor(model => model.Address.Longitude) 
       @Html.ValidationMessageFor(model => model.Address.Longitude) 
       <div class="clear"></div> 
      </div> 

      <div class="st-form-line"> 
       <span class="st-labeltext">@Html.LabelFor(model => model.Address.Latitude)</span> 
       @Html.EditorFor(model => model.Address.Latitude) 
       @Html.ValidationMessageFor(model => model.Address.Latitude) 
       <div class="clear"></div> 
      </div> 
</div> 

我有以下的jQuery(此處所說的給我一個問題位):

$('a.GetPosition').live("click", function (evt) { 
     evt.preventDefault(); 
     $(this).next().show(); 
     var mapElement = $(this).closest('.body').find('.map'); 
     var latElement = $(this).closest('.body').find('[id$=__Address_Latitude]'); 
     var longElement = $(this).closest('.body').find('[id$=__Address_Longitude]'); 
     showAddress(mapElement, latElement, longElement); 
    }); 

    // Google Map 
    var map; 
    function showAddress(mapElement, latElement, longElement) { 
     var myLatlng = new google.maps.LatLng(40.713956, -74.006653); 

     var myOptions = { 
      zoom: 8, 
      center: myLatlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 
     map = new google.maps.Map(mapElement, myOptions); 

     var marker = new google.maps.Marker({ 
      draggable: true, 
      position: myLatlng, 
      map: map, 
      title: "choose location" 
     }); 

     google.maps.event.addListener(marker, 'click', function (event) { 
      latElement.val(event.latLng.lat().toFixed(5)); 
      longElement.val(event.latLng.lng().toFixed(5)); 
     }); 
    } 

現在我只是硬編碼默認地圖位置'40.713956,-74.006653',但我會改變這個使用真實世界的地址,一旦我可以讓地圖顯示正確。

我知道問題歸結爲'mapElement',但我不確定是什麼錯誤。如果我評論我們的showAddress函數調用並將一些文本輸出到mapElement中,我可以看到文本,所以它似乎找到了正確的dom loction。

我可以在這裏嘗試的任何想法?謝謝你的幫助。

感謝,

豐富

回答

0

所以做一些研究很清楚之後,谷歌地圖只作品,如果我用一個元素的ID 。如果我把它傳給一個班,它就不起作用。

要解決此問題,我必須在點擊顯示地圖的按鈕時動態添加具有唯一ID的div。

我的HTML看起來像這樣:

<div class="body"> 
     <div class="st-form-line"> 
        <span class="st-labeltext">Location</span> 
        <a href="#" class="GetPosition">Get Latitude &amp; Longitude positions based on above address details.</a> 
        <div class="mapContainer" style="display:none;"> 
        <p>If the map position is incorrect simply drag the pointer to the correct location.</p> 
        <p>@Html.LabelFor(model => model.Address.Longitude) @Html.EditorFor(model => model.Address.Longitude) @Html.LabelFor(model => model.Address.Latitude) @Html.EditorFor(model => model.Address.Latitude) <br /> 
        @Html.ValidationMessageFor(model => model.Address.Longitude) @Html.ValidationMessageFor(model => model.Address.Latitude)</p><br /> 
        <div class="clear"></div> 
       </div> 
     </div> 
    </div> 

中的JavaScript看起來像這樣:

var i = 1; 
    $('a.GetPosition').live("click", function (evt) { 
     evt.preventDefault(); 
     // build up address string for map 
     var address = //added my address textboxes here - removed for brevity; 
     // find the map container and make it visible 
     var mapContainer = $(this).next(); 
     mapContainer.show(); 
     // create a new map div with unique id 
     var mapId = 'map' + i++; 
     $("<div></div>").attr("id", mapId).attr("style", "width: 600px; height: 350px;").appendTo(mapContainer); 
     // find the lat long textboxes and pass to the Google map function so we can populate with co-ordinates 
     var latElement = $(this).closest('.body').find('[id$=__Address_Latitude]'); 
     var longElement = $(this).closest('.body').find('[id$=__Address_Longitude]'); 
     showAddress(mapId, address, latElement, longElement); 
     // finally hide the button to avoid other map divs being generated 
     $(this).hide(); 
    }); 
var map; 
var marker; 
function showAddress(mapId, address, latElement, longElement) { 

    var map = new google.maps.Map(document.getElementById(mapId), { 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     zoom: 15 
    }); 

    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 
     'address': address 
    }, 
     function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       marker = new google.maps.Marker({ 
        draggable: true, 
        position: results[0].geometry.location, 
        map: map 
       }); 
       map.setCenter(results[0].geometry.location); 
       latElement.val(results[0].geometry.location.lat().toFixed(5)); 
       longElement.val(results[0].geometry.location.lng().toFixed(5)); 

       google.maps.event.addListener(marker, 'dragend', function (event) { 
        latElement.val(event.latLng.lat().toFixed(5)); 
        longElement.val(event.latLng.lng().toFixed(5)); 
       }); 
      } 
     }); 
} 

顯然仍然存在與上面的代碼需要進行一些微調錯誤檢查需要加入,但希望這可以幫助其他人開始使Google地圖與動態表單一起工作。

0

加載靜態緯度和LNG示例代碼:

var initialLocation = new google.maps.LatLng(40.713956, -74.006653); 
    var zoom = 4; 

     var options = { 
      zoom: zoom, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 
     map = new google.maps.Map(document.getElementById("map_canvas"), options); 
     map.setCenter(initialLocation); 
     map.setZoom(zoom); 

上面的例子將顯示在您的div 「map_canvas」 的靜態地圖。 您也可以使用谷歌地圖的一個更重要的因素,即地理編碼器:這將幫助你在谷歌地圖繪製地址

var mygc = new google.maps.Geocoder(); 
mygc.geocode({ 'address': address }, 
    function (results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        initialLocation = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); 

        map.setCenter(initialLocation); 
        map.setZoom(zoom); 
       } 
      } 
    ); 
+0

謝謝你的回答Anil。不幸的是,我的問題不是要讓Google地圖顯示一次,而是要讓它顯示爲具有類而不是id的特定div。我的代碼似乎找到了正確的元素,但Google地圖似乎並不喜歡我將此元素傳遞給它。 – 2012-03-13 15:54:48

2

MapController看起來是這樣的:

public ActionResult Index() 
     { 

      string markers = "["; 
      string conString = ConfigurationManager.ConnectionStrings["PTS"].ConnectionString; 
      SqlCommand cmd = new SqlCommand("SELECT * FROM Project"); 
      using (SqlConnection con = new SqlConnection(conString)) 
      { 
       cmd.Connection = con; 
       con.Open(); 
       using (SqlDataReader sdr = cmd.ExecuteReader()) 
       { 
        while (sdr.Read()) 
        { 
         markers += "{"; 
         markers += string.Format("'title': '{0}',", sdr["projecttitle"]); 
         markers += string.Format("'address': '{0}',", sdr["address"]); 
         markers += string.Format("'lat': '{0}',", sdr["latitude"]); 
         markers += string.Format("'lng': '{0}',", sdr["longitude"]); 
         markers += string.Format("'description': '{0}'", sdr["explanation"]); 
         markers += "},"; 
        } 
       } 
       con.Close(); 
      } 

      markers += "];"; 
      ViewBag.Markers = markers; 
      return View(); 
     } 

項目:你的數據庫表名|標題,地址,說明:信息要出現在地圖

索引視圖上看起來是這樣的:

@model PTS.Models.Project 

@{ 

ViewBag.Title = "Index"; 
Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<html> 
<head> 
    <style> 
     .angular-google-map-container { 
      height: 300px; 
      box-shadow: 2px 2px 3px 3px lightgrey; 
     } 

     .angular-google-map { 
      width: 80%; 
      height: 100%; 
      margin: auto 0px; 
     } 
    </style> 
    <title>Simple Map</title> 
    <meta name="viewport" content="initial-scale=1.0"> 
    <meta charset="utf-8"> 
    <script src="http://code.jquery.com/jquery-1.12.2.min.js"></script> 
    <script src="https://maps.googleapis.com/maps/api/js?key=yourmapkey&libraries=places"></script> 
    <style> 
     html, body { 
      height: 100%; 
      margin: 0; 
      padding: 0; 
     } 

     #map { 
      height: 100%; 
      width: 1500px; 
     } 
    </style> 


    <meta name="viewport" content="width=device-width" /> 
    <title>Index</title> 
</head> 
<body> 
    <br /><br /> 


    <style> 
     #content { 
      border: 1px solid black; 
      margin-top: 2px; 
      background-image: url('/Content/images/infowindow.jpg'); 
      /*background: #098;*/ 
      color: #FFF; 
      font-family: Verdana, Helvetica, sans-serif; 
      font-size: 12px; 
      padding: .1em 1em; 
      -webkit-border-radius: 2px; 
      -moz-border-radius: 2px; 
      border-radius: 2px; 
      text-shadow: 0 -1px #000000; 
      -webkit-box-shadow: 0 0 8px #000; 
      box-shadow: 0 0 8px #000; 
     } 
    </style> 


    <script> 

     var markers = @Html.Raw(ViewBag.Markers); 
     function myMap() { 
      var mapCanvas = document.getElementById("map"); 

      var mapOptions = { center: new google.maps.LatLng(markers[0].lat, markers[0].lng), zoom: 8, 
       mapTypeId: google.maps.MapTypeId.ROADMAP }; 
      var map = new google.maps.Map(mapCanvas, mapOptions); 

      for (i = 0; i < markers.length; i++) { 
       var data = markers[i] 
       var myLatlng = new google.maps.LatLng(data.lat, data.lng); 
       var marker = new google.maps.Marker({ 
        position: myLatlng, 
        map: map, 
        title: data.title 
       }); 

       var cityCircle = new google.maps.Circle({ 
        strokeColor: '#FF0000', 
        strokeOpacity: 0.8, 
        strokeWeight: 2, 
        fillColor: '#FF0000', 
        fillOpacity: 0.35, 
        map: map, 
        center: myLatlng, 
        radius: 19999.45454, 
        position: myLatlng, 
        draggable:false 
       }); 
       var contentString = '<div id="content">' + 
             '<b> Project Title : </b> ' + 
     data.title+ '</div>' + '<div id="content">'+ 
             '<b> Address : </b> ' + data.address 
     + '</div>' + '<div id="content">' + '<b> Explanation : </b> ' + data.description + '</div>' + '</div>' ; 


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


       marker.infowindow = infowindow; 

       marker.addListener('click', function() { 
        return this.infowindow.open(map, this); 
       }) 


       google.maps.event.addListener(marker, 'click', function() { 
        this.infowindow.open(map, this); 
       }); 
      } 
     } 


    </script> 

    <div id="map" style="width: 1500px; height: 1000px"></div> 
    <script src="https://maps.googleapis.com/maps/api/js?key=yourmapkey&callback=myMap"></script> 


</body> 
</html> 

這種方式,我們可以動態地顯示地圖,並使用我們的地圖上我們的網站或其他的項目。希望這可以幫助 !

相關問題