谷歌地图不在ajax加载页面的中心

时间:2013-06-10 10:09:26

标签: google-maps

在webapp中我使用ajax加载页面(带地图的googlemap.asp)。

我使用jquery.load在div中加载“googlemap.asp”,它显示左上角的中心。当我以这种方式加载地图时,它无法正确渲染地图。

但是如果我只是直接在浏览器中加载“googlemap.asp”(没有ajax)那么它会显示正确,所以当我用ajax加载它时,我想我必须以某种方式重新刷新它?

这就是我所拥有的:

<div id="map_canvas" style="height:600px; width:320px;" ></div>

window.onload=googleMaploadScript();
var address1 = document.getElementById('address').value;

function googleMaploadScript() {
    var script =document.createElement("script");
    script.type="text/javascript";
    script.src="http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);  
    }




var geocoder;
var map;
function initialize() {

  geocoder = new google.maps.Geocoder();
  var mapOptions = {
    zoom: 15,
    center: new google.maps.LatLng(57.109577,12.286513),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);  
  codeAddress(address1);

}

function codeAddress(address) {
  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);
    }
  });

}

因为我加载.load的页面是隐藏的,直到你导航到div,然后它变得可见,也许这是问题? 我想我以某种方式加载错误的顺序,这就是为什么它不能正确渲染,或者可能是div在开始时不可见?

感谢任何意见,谢谢。

2 个答案:

答案 0 :(得分:2)

我之前遇到同样的问题

不要使用

 geocoder.geocode( { 'address': address}, function(results, status) {.....

使用ajax加载页面时,“geocoder.geocode ...”无法返回正确的geometry.location。
我不知道为什么

但是当我尝试更改代码时,地图正在运行

我的代码就像

    $.ajax({
        url: "http://maps.googleapis.com/maps/api/geocode/json?address="+youraddress+"&sensor=false",
        type : "POST",
        dataType: "json",
        cache: false,
        success: function(result){
           if(result.results.length){
            lat=result.results[0].geometry.location.lat;
            lng=result.results[0].geometry.location.lng;

           //map
           var map     
            var latlng = new google.maps.LatLng(lat, lng);     
            var mapOptions = {
              zoom: 15,
              center: latlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            map = new google.maps.Map(document.getElementById('map_canvas1'), mapOptions);
          ............

答案 1 :(得分:1)

Developers should trigger this event on the map when the div changes size:

google.maps.event.trigger(map, 'resize')