Asp.net mvc 3 如何将谷歌地图与动态表单结合使用

Asp.net mvc 3 如何将谷歌地图与动态表单结合使用,asp.net-mvc-3,google-maps-api-3,mvc-editor-templates,Asp.net Mvc 3,Google Maps Api 3,Mvc Editor Templates,我使用MVC模板允许用户添加多个地址。他们单击一个按钮,这将使用jquery调用我的模板,并生成表单。如果他们想添加另一个位置,他们会再次单击按钮并设置另一个表单,以此类推。这个模板工作得很好,但我在这些模板中使用谷歌地图时遇到了一些问题 在这个场景中使用GoogleMaps的原因是为了提供一个很好的界面,为您正在添加的位置添加经度和纬度。我在这里使用类而不是id,因为屏幕上可能有任意数量的地址区域 在我的mvc模板中,我有以下标记: <div class="body">

我使用MVC模板允许用户添加多个地址。他们单击一个按钮,这将使用jquery调用我的模板,并生成表单。如果他们想添加另一个位置,他们会再次单击按钮并设置另一个表单,以此类推。这个模板工作得很好,但我在这些模板中使用谷歌地图时遇到了一些问题

在这个场景中使用GoogleMaps的原因是为了提供一个很好的界面,为您正在添加的位置添加经度和纬度。我在这里使用类而不是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>
现在,我只是在默认地图位置“40.713956,-74.006653”硬编码,但一旦我能够正确显示地图,我会将其更改为使用真实世界的地址

我知道问题出在“mapElement”上,但我不确定到底出了什么问题。如果我对showAddress函数调用进行注释并将一些文本输出到mapElement中,我可以看到这些文本,因此它看起来确实找到了正确的dom位置

我能在这里试试吗?谢谢你的帮助

谢谢


Rich

装载静态Lat和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\u 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);
                }
            }
    );

所以,在做了一些研究之后,很明显谷歌地图只有在我使用元素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>  
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));
               });
           }
       });
}

位置
如果地图位置不正确,只需将指针拖动到正确的位置即可

@Html.LabelFor(model=>model.Address.Longitude)@Html.EditorFor(model=>model.Address.Longitude)@Html.LabelFor(model=>model.Address.Latitude)@Html.EditorFor(model=>model.Address.Latitude)
@Html.ValidationMessageFor(model=>model.Address.Longitude)@Html.ValidationMessageFor(model=>model.Address.Latitude)


JavaScript如下所示:

    <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>  
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));
               });
           }
       });
}
var i=1;
$('a.GetPosition').live(“单击”),函数(evt){
evt.preventDefault();
//建立映射的地址字符串
var address=//在此处添加了“我的地址”文本框-为简洁起见已删除;
//找到地图容器并使其可见
var mapContainer=$(this.next();
show();
//创建具有唯一id的新映射div
var mapId='map'+i++;
$(“”).attr(“id”,mapId).attr(“样式”,“宽度:600px;高度:350px;”).appendTo(mapContainer);
//找到lat-long文本框并传递到谷歌地图功能,这样我们就可以填充坐标
var LATELENT=$(this).closest('.body').find('[id$=\u地址\u纬度]);
var longElement=$(this).closest('.body').find('[id$=\u地址\u经度]);
showAddress(mapId、address、LateElement、longElement);
//最后隐藏按钮以避免生成其他贴图div
$(this.hide();
});
var映射;
var标记;
函数showAddress(mapId、address、LateElement、longElement){
var map=new google.maps.map(document.getElementById(mapId){
mapTypeId:google.maps.mapTypeId.ROADMAP,
缩放:15
});
var geocoder=new google.maps.geocoder();
地理编码({
“地址”:地址
},
功能(结果、状态){
if(status==google.maps.GeocoderStatus.OK){
marker=新的google.maps.marker({
真的,
位置:结果[0]。geometry.location,
地图:地图
});
map.setCenter(结果[0].geometry.location);
val(结果[0].geometry.location.lat().toFixed(5));
longement.val(结果[0].geometry.location.lng().toFixed(5));
google.maps.event.addListener(标记'dragend',函数(事件){
val(event.latLng.lat().toFixed(5));
val(event.latLng.lng().toFixed(5));
});
}
});
}
显然,由于需要添加错误检查等,上述代码仍需要进行一些微调,但希望这能帮助其他人开始使用动态表单使用Google地图。

MapController如下所示:

    <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>  
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));
               });
           }
       });
}
项目:您的数据库表名称|标题、地址、描述:您希望在地图上显示的信息

索引视图如下所示:

    <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>  
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));
               });
           }
       });
}
@model PTS.Models.Project
@{
ViewBag.Title=“Index”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
.google地图容器{
高度:300px;
盒影:2件2件3件3件浅灰色;
}
.谷歌地图{
宽度:80%;
身高:100%;
保证金:自动0px;
}
简单地图
html,正文{
身高:100%;
保证金:0;
填充:0;
}
#地图{
身高:100%;
宽度:1500px;
}
指数


#内容{ 边框:1px纯黑; 边缘顶部:2倍; 背景图片:url('/Content/images/infowindow.jpg'); /*背景:#098*/ 颜色:#FFF; 字体系列:Verdana、Helvetica、无衬线; 字体大小:12px; 填充:.1em-1em; -webkit边界半径:2px; -moz边界半径:2px;