0

MVCテンプレートを使用して、複数の住所を追加できるようにします。彼らはボタンをクリックするとjqueryを使用してテンプレートが呼び出され、フォームが生成されます。別の場所を追加したい場合は、もう一度ボタンをクリックし、別のフォームが設​​定されているなどです。このテンプレートは正常に機能しますが、これらのテンプレート内でGoogleマップを使用するのに問題があります。Googleマップを動的フォームで使用する方法

このシナリオでGoogleマップを使用する理由は、追加する場所に経度と緯度を追加するための素晴らしいインターフェースを提供するためです。私は画面上に任意の数のアドレスエリアが存在する可能性があるので、IDの代わりにここでクラスを使用しています。私はちょうどよ今の

$('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)); 
     }); 
    } 

:私は、次のjQueryを(これは私に問題を与えているビットである)を持つ

<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> 

:私は次のマークアップを持っている私のMVCテンプレートで

'40 .713956、-74.006653 'のデフォルトのマップ位置でハードコーディングしていますが、マップを正しく表示するには、実際のアドレスを使用するようにこれを変更します。

私は問題が 'mapElement'にあることを知っていますが、何が間違っているのかは分かりません。 showAddress関数の呼び出しにコメントし、mapElementに何らかのテキストを出力すると、テキストが表示されるので、正しいdom loctionが見つかったように見えます。

私がここで試すことができるアイデアはありますか?ご協力いただきありがとうございます。

おかげで、静的な緯度とLNGをロードするための

リッチ

答えて

0

上のアドレスを描画するのに役立ちますので、いくつかの研究を行った後、それは私が要素のIDを使用している場合、Googleマップにのみ動作することは明らかです。私はそれをクラスに渡すとうまくいきません。

この問題を回避するには、地図を表示するボタンがクリックされたときに一意の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

例コード:

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" に静的な地図を表示します。 あなたはまた、Googleマップすなわちジオコーダのもう一つの重要な要素を使用することができます。これは、Googleマップ

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マップではこの要素をどのように渡すのが好きではないようです。 –

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> 

このよう他のプロジェクト。お役に立てれば !

関連する問題