【问题标题】:How do I to load map when page is already loaded?页面已加载时如何加载地图?
【发布时间】:2017-11-09 16:04:53
【问题描述】:

我有一个页面,我需要按地址加载地图以查看位于该点的属性。为此,我找到了Google Maps API,但我还不能这样做。我正在尝试一个我在文档中看到的示例,但它仍然无法正常工作并且不会引发任何异常。

Here 文档。

我该怎么做?

正在加载 Google Maps API

<script src="https://maps.google.com/maps/api/js?key=AIzaSyA8JZPv2N9bE0OQABj6hKO9QZb0kH32l"></script>

按地址加载地图的脚本

$(document).ready(function () {
    initialize();
    codeAddress();   
});

var geocoder;
var map;
function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        zoom: 8,
        center: latlng
    }
    map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
}

function codeAddress() {
    var address = document.getElementById('myAddress').value;    
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == '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);
        }
    });
}

HTML

<div id="gmap"></div>

<!--my address-->
@Html.HiddenFor(model => model.myAddress)

【问题讨论】:

  • 您看到警报错误了吗?
  • 您的代码看起来不错。现在发生了什么?你有任何脚本错误吗?

标签: asp.net-mvc google-maps-api-3


【解决方案1】:

我终于解决了这个问题。

function loadByAddress() {
    var address = $('#myAddress').val();
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == 'OK') {
            var latlng = new google.maps.LatLng(results[0].geometry.location.lat, results[0].geometry.location.lng);
            var myOptions = {
                zoom: 20,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.SATELLITE
            };
            var map = new google.maps.Map(document.getElementById("gmap"), myOptions);
            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", loadByAddress);

【讨论】:

  • 出了什么问题?
猜你喜欢
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多