2015-04-24 101 views
-1

我一直在寻找一个小时的解决方案,但找不到一个,我希望有人可以帮助我,因为我是新的谷歌API,所以这就是我想要做的:我有一个区域和城市的动态下拉和基于用户选择的表单,这将更新谷歌地图上的标记,infowindow显示地址,经纬度和长..我的问题是提交表单,地图显示空白..这里是我的代码:更新表格提交谷歌地图

var Latlong = new google.maps.LatLng(61.10802786270912, 8.883177374999718); 
var map; 
var geocoder; 
var marker; 

function initialize() { 
    geocoder = new google.maps.Geocoder(); 
      var mapOptions = { 
      zoom: 5, 
      center: Latlong 
      } 
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 

      marker = new google.maps.Marker({ 
       position: Latlong, 
       map: map, 
       draggable:true, 
       title: "Drag Me!" 
      }); 

      infowindow=new google.maps.InfoWindow(); 
      infowindow.setOptions({ 
       content: "<strong>Drag Marker</strong>"  
      }); 

      infowindow.open(map,marker);   

} 

function newmap(selectedregion, selectedcity){ 
    var address = selectedregion+ "," +selectedcity; 

    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      map.setCenter(results[0].geometry.location); 
      map.setZoom(18); 
      marker.setMap(null); 
      marker = new google.maps.Marker({ 
       map: map, 
       position: results[0].geometry.location, 
       draggable:true 
      }); 
     infowindow=new google.maps.InfoWindow(); 
     infowindow.setOptions({ 
      content: "test" 
     }); 
     infowindow.open(map,marker); 

     } else { 
      alert('Geocode was not successful for the following reason: ' + status); 
     } 
     }); 

} 

所以这个代码将被要求重新加载页面:

$(window).load(function() { 
var selectedregion = document.getElementById('region').value; 
var selectedcity = document.getElementById('city').value; 

if(selectedregion == "" && selectedcity == ""){ 
    initialize(); 
}else{ 
    newmap(selectedregion, selectedcity); 
} 
}); 

它更迭在第一次加载时调用初始化函数,但它没有成功处理newmap函数。我避免使用这个:google.maps.event.addDomListener(窗口,'加载',初始化);因为每次表单提交时,googlemap都会转到其默认的LatLng(61.10802786270912,8.883177374999718)。有人可以帮我这个请..

+1

你的代码,尤其是newmap功能与我合作。你必须向你展示表单代码,因为可能存在这个问题。你的表单是否会返回错误的提交事件? – Blauharley

+0

表单在提交时返回true,我试图提醒(selectedregion)和alert(selectedcity),它将值返回给我,所以nothings错误的形式..我试图改变newmap()函数testmap()的代码在初始化(),只是改变LatLng的坐标,它运作良好,我只是无法找到newmap()的错误。 –

+0

,因为我写它与我很好,所以叫它一天;) – Blauharley

回答

2

您打电话initializenewmap在您的onload功能。

newmap取决于初始化正在运行,以实例化地理编码器和地图。

这个工作对我来说:

$(window).load(function() { 
    var selectedregion = document.getElementById('region').value; 
    var selectedcity = document.getElementById('city').value; 
    initialize(); 

    if(selectedregion == "" && selectedcity == ""){ 

    }else{ 
    newmap(selectedregion, selectedcity); 
    } 
}); 

proof of concept fiddle

+0

哇!我没有意识到,那个工作非常好!非常感谢你的关注!对此,我真的非常感激! :) –