Google maps API根据select选项初始化地图

时间:2017-12-01 09:42:03

标签: javascript google-maps-api-3

我必须根据在select中选择一个选项而触发的POST请求来显示地图的标记,但是有些东西丢失......

我有这个选择

<select id="locationSelector" class="selectpicker">
<option th:each="l : ${locations}" th:value="${l.locationId}" th:text="${l.name}"></option>
</select>

然后是我的剧本

    var id = $('#locationSelector :selected').val();

    function updateLocation(){ //take the objects
            console.log('locationId is ' + id);

              $.ajax({
              type: "POST",
              url: "/admin/map/vehicles",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              data: {
                locationId:id
            },
              success: function (response) {
                          console.log(response);
                         location = response.location;
                         vehicles = response.vehicles;

                      },
               error: function(response){
                   alert(response.responseJSON.message);
               }
                 });
            }


function setVehicleMarkers(map, cars) { //create the markers
            var infowindow = new google.maps.InfoWindow();

            vehicles.forEach(function (arrayItem) {
                var vehicle = arrayItem;
                var myLatLng = new google.maps.LatLng(vehicle.lat, vehicle.lng);

                var vehicleIcon;
                }               }

                var icon = { url : '/images/vehicles/'+vehicleIcon+'.png',
                        size : new google.maps.Size(47, 63),
                        origin : new google.maps.Point(0, 0),
                        anchor : new google.maps.Point(0, 63)};
                var vehicleMarker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    title: vehicle.plateId,
                    zIndex: vehicle.vehicleId,
                    icon: icon

                });

                 var contentString = '<div class="text-center"><b><a href="/admin/vehicle/'+ vehicle.vehicleId + '">'+vehicle.plateId + '</a></b><br/><br/>';
                  google.maps.event.addListener(infowindow, 'domready', function(event){ 
})

                  google.maps.event.addListener(vehicleMarker, 'click', function(content){
                      return function(){
                      infowindow.setContent(content);
                      infowindow.open(map, this);
                      }
                  }(contentString));

                arrVehicles.push(vehicleMarker);

            });

        }

function initMap() { //initialize the map
            updateLocation();
            var myOptions = {
                    zoom:9,
                    center : new google.maps.LatLng(location.lat, location.lng),
                    mapTypeId: google.maps.MapTypeId.ROADMAP,

            };

var map = new google.maps.Map(document.getElementById('map'), myOptions);

            //create empty LatLngBounds object
            var bounds = new google.maps.LatLngBounds();


            //now fit the map to the newly inclusive bounds
            google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
          this.setZoom(map.getZoom()-1);

          if (this.getZoom() > 15) {
            this.setZoom(15);
          };
        });


            map.fitBounds(bounds);
            map.panToBounds(bounds);
            console.log(vehicles);
            setVehicleMarkers(map, vehicles);

        }

问题是我的控制器一直说在进行POST时没有定义参数locationId,应该是因为初始化地图时,locationSelector尚未加载...我试图包装在document.ready()中的initMap,确保在加载所有内容时加载,然后google maps api调用

<script
        src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;key=AAAAAAAAAAAAA&amp;callback=initMap"
        async="async" defer="defer"></script>

给我一​​个错误

2 个答案:

答案 0 :(得分:0)

您可以这样做:

function initMap(){
    $(function(){
       // Ready to retrieve the ID and initialise the map.
    });
}

此外,您应该在ajax setVehicleMarkers回调中调用success函数,并在初始化地图时调用updateLocation

为确保在使用之前初始化所有变量和HTML元素,您应该执行以下操作:

function updateLocation(map){ 
      $.ajax({
         .....
         ,success: function (response) {
                     location = response.location;
                     vehicles = response.vehicles;
                     setVehicleMarkers(map, vehicles);
                  },
           ....
        });
}


function setVehicleMarkers(map, cars) { 
     ....
}

function initMap() {
   $(function(){
      // Initialise map
      var map = ....
      id = $('#locationSelector :selected').val();
      updateLocation(map);
   })
}

答案 1 :(得分:0)

尝试在initMap之前将此行添加到文档就绪。

var id = $('#locationSelector :selected').val();