【问题标题】:Google map on ajax successajax成功的谷歌地图
【发布时间】:2017-09-16 08:22:01
【问题描述】:

我在 选择下拉更改 上有以下 Ajax 请求,它只是从控制器获取记录,循环遍历每个记录并获取 latitude | longitude将其推送到数组

然后在同样的 ajax 成功中,我将该 lat 和 lng 数组传递给谷歌地图。

但是地图没有显示出来。

$(document).ready(function() {
   $('.selectCity').change(function() {
    var city = $(this).val();
    $.ajax({
      type: 'GET',
      url: '/riders/location/track',
      data: {
        'city': city
      },
      success: function(data) {
        var lat = [];
        var lng = [];

        //Get Locations and push it to lat and lng
        $.each(data, function(index, value) {
          $.each(value, function(index1, value1) {
            console.log(value1.rider_location.lat);
            lat.push(value1.rider_location.lat);
            lng.push(value1.rider_location.lng);
          });
        });

        //Google Map
        google.maps.event.addDomListener(window, 'load', init);

        function init() {

          var locations = [
            ['Rider', lat, lng]
          ];

          var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: new google.maps.LatLng(lat, lng),
            mapTypeId: google.maps.MapTypeId.ROADMAP
          });
          var infowindow = new google.maps.InfoWindow();
          var marker, i;
          for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
              position: new google.maps.LatLng(locations[i][1], locations[i][2]),
              map: map
            });
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
              return function() {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
              }
            })(marker, i));
          }
        }
      }
    });
  });
});

另外,请提出最佳做法。

【问题讨论】:

  • 您的地图可能已经完全加载,您是否尝试过监听“空闲”事件,例如 answer?否则,您还可以将此 google-load-listener 移到 ajax-success-function 之外,以便在 ajax 调用完成之前显示您的地图等。
  • @Blauharley 有道理,请把你的评论作为答案,一点代码解释会很棒。

标签: javascript php jquery ajax google-maps


【解决方案1】:

当然,我可以在上面发表评论作为答案。

您还可以使用callback-parameter (HTML) 在 script-url 中收听“google-maps-ready”事件:

<script type="text/javascript"
  src="http://maps.googleapis.com/maps/api/js?libraries=geometry,places&callback=initialize">
</script>

JS:

// In this way you have to define a function called initialize which should be defined globally otherwise it can not be found by the google-library.

// unfortunately this map-variable is defined globally here but you can also wrap the whole code below by using an IIFE.
var map; 
function initialize() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    // you might set a center here or wait untill you have got some markers fetched via ajax, you can then use the first/last or some other marker respecetive it's position(lat,long) to set as "starting point"
    //center: {lat: LAT, lng: LONG }
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
}

// Although I have no access to your website to test this code below, it might be done in this way:
$(document).ready(function () {
  $('.selectCity').change(function () {
    var city = $(this).val();
    $.ajax({
      type: 'GET',
      url: '/riders/location/track',
      data: {
        'city': city
      },
      success: function (data) {
        var positions = [];
        //Get Locations and push it to lat and lng
        // you can also use just one array to insert all locations and "labels" into
        $.each(data, function (index, value) {
          $.each(value, function (index1, value1) {
            console.log(value1.rider_location.lat);
            positions.push({
              lat: value1.rider_location.lat,
              lng: value1.rider_location.lng,
              content: 'Rider' // do you get some text with each location?
            });
          });
        });
        // set "starting point" afterwards
        map.setCenter({
          lat: positions[0].lat,
          lng: positions[0].lng
        });
        var infowindow = new google.maps.InfoWindow();
        var marker,
        i;
        for (i = 0; i < positions.length; i++) {
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(positions[i].lat, positions[i].lng),
            map: map
          });
          google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
              infowindow.setContent(positions[i].content);
              infowindow.open(map, marker);
            }
          }) (marker, i));
        }
      }
    });
  });
});

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2013-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多