在表单提交上更新谷歌地图

时间:2015-04-24 18:48:35

标签: javascript jquery forms google-maps google-maps-api-3

我一直在寻找一个解决方案几个小时但找不到一个,我希望有人可以帮助我,因为我是谷歌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(window,'load',initialize);因为每次表单提交时,googlemap都会转到默认的LatLng(61.10802786270912,8.883177374999718)。有人可以帮我这个吗..

1 个答案:

答案 0 :(得分:2)

您在onload函数中调用initializenewmap

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