Google Maps API v3 / MVC 4 -对地址进行地理编码,该地址传递给MVC 4应用程序中的(部分视图

本文关键字:MVC 地址 应用程序 址传 视图 v3 API Maps Google 编码 | 更新日期: 2023-09-27 18:08:11

我有一个搜索结果列表。在每个结果旁边都有一个按钮,当单击该按钮时,将启动包含Bootstrap模式的部分视图。

模态是强类型的,传入的对象表示一个有地址的住宅属性。地址显示在模态头中。

我试图获得地址并将其传递给JS函数,该函数将对其进行地理编码并在模态中的选项卡上显示它。

我试过了:

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h4 id="myModalLabel" data-id="@Model.Address.Line1,@if (Model.Address.Line2 != null)
    { @Model.Address.Line2; },@Model.Address.TownCity,@Model.Address.County">
        // display the address
    </h4>
</div>
<div class="modal-body">
    <div id="map-canvas" style="width: 400px; height: 400px">map canvas</div>
</div>
<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>

JS作为partial的结尾:

<script type="text/javascript">
initialize();
var geocoder;
var map;
function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
}
function codeAddress() {
    var address = $('#myModalLabel').attr('data-id');
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}
google.maps.event.addDomListener(window, "load", initialize);

所以我试图将data-id属性添加到显示地址的模态标签,然后在codeAddress()函数中选择。

显示硬编码的默认地图,但没有发生地理编码。有人能给我指个正确的方向吗?也许给出一种更优雅的方式从模型中获取地址并将其传递给codeAddress()

Google Maps API v3 / MVC 4 -对地址进行地理编码,该地址传递给MVC 4应用程序中的(部分视图

我使用的是来自谷歌教程的代码,他们在一个按钮点击事件中调用codeAddress()。我实际上并没有调用codeAddress()

initialize()解决问题后添加codeAddress()