如何在页面加载后加载地图?

时间:2017-11-09 16:04:53

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

我有一个页面,我需要通过地址加载地图以查看该点的属性。为此,我找到了Google Maps API,但我还不能做到这一点。我尝试了一个我在文档中看到的例子,但它仍然不起作用,也没有抛出任何异常。

Here de documentation。

我怎么能这样做?

加载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)

1 个答案:

答案 0 :(得分:-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);