javascript - 如何在 Ajax 调用后使用标记渲染 Google map

标签 javascript jquery google-maps

下面程序的目标是从网络服务中获取 json(经/纬度)数据,然后将接收到的数据插入到标记中,然后用标记渲染 Google map 。我尝试了各种策略(例如,在这里和那里保留 ajax 调用),但它不起作用,无论 Ajax 调用在 Google map 渲染之后发生的原因是什么,并且它对标记没有做任何事情。(有时它不会根本不渲染 map )。谷歌地图给出的示例按定义工作,但根据我的目标,它不起作用。请您向我建议我在这里缺少什么。

   <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">

jQuery(function($) {
// Asynchronously Load the map API 
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script); });

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);
    var latlngData = 0;    

            $.ajax({
  type:'GET',
  url: 'http://localhost:8080/xyz-service/xyz/xyzData/24252627',
  dataType: 'json',
  success: function(data) {
  latlngData = data; 
  console.log(latlngData);  
    },
    error: function(){
        $('#output ul').append('<li>Error');
    }
 });


// Info Window Content
    var infoWindowContent = [
        ['<div class="info_content">' +
        '<h3>London Eye</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' +        '</div>'],
        ['<div class="info_content">' +
        '<h3>Palace of Westminster</h3>' +
        '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
        '</div>']
    ];

    // Display multiple markers on a map, same info for everyone, just an example
    var infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map, fetching avg_gps_latitude,   avg_gps_longitude from latlngData, received from ajax call ( but it dodn't work)

    for( i = 0; i < latlngData.length; i++ ) {
        var position = new google.maps.LatLng(latlngData[i].avg_gps_latitude,latlngData[i].avg_gps_longitude);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: latlngData[i].ssid
        });

        // Allow each marker to have an info window    
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[0][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);
    }

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
        this.setZoom(14);
        google.maps.event.removeListener(boundsListener);
    });

}


    </script>
    <meta charset="utf-8">
    <title>Simple markers</title>
    <style>
      #map_wrapper {
    height: 400px;
}

#map_canvas {
    width: 100%;
    height: 100%;
}
    </style>
  </head>
  <body>


<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>




  </body>
</html>

最佳答案

我建议进行以下更改:

1) 自 jQuery.ajax()默认情况下异步,初始化标记时latlngData可能尚未填充。例如,将标记初始化放入 success 回调或 .done() 函数(参见下面的示例)

2) 您可以使用 google.maps.event.addDomListener(window, 'load',initialize);

,而不是动态加载 Google Maps API

修改示例

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);
    var latlngData = 0;

 

    // Info Window Content
    var infoWindowContent = [
        ['<div class="info_content">' +
        '<h3>London Eye</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' + '</div>'],
        ['<div class="info_content">' +
        '<h3>Palace of Westminster</h3>' +
        '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
        '</div>']
    ];

    // Display multiple markers on a map, same info for everyone, just an example
    var infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map, fetching avg_gps_latitude,   avg_gps_longitude from latlngData, received from ajax call ( but it dodn't work)
    loadLocations().done(function (latlngData) {

        for (i = 0; i < latlngData.length; i++) {
            var position = new google.maps.LatLng(latlngData[i].avg_gps_latitude, latlngData[i].avg_gps_longitude);
            bounds.extend(position);
            marker = new google.maps.Marker({
                position: position,
                map: map,
                title: latlngData[i].ssid
            });

            // Allow each marker to have an info window
            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infoWindow.setContent(infoWindowContent[0][0]);
                    infoWindow.open(map, marker);
                }
            })(marker, i));

            // Automatically center the map fitting all markers on the screen
            map.fitBounds(bounds);
        }


    });

    


  
    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
        this.setZoom(14);
        google.maps.event.removeListener(boundsListener);
    });
}



function loadLocations()
{
    return $.ajax({
        type: 'GET',
        url: 'https://gist.githubusercontent.com/vgrem/5be61555df259d8cbefe/raw/9ca707b3141a29f58c8281684dfc778a5e6eb035/LondonData.json',
        dataType: 'json'
    });
}

google.maps.event.addDomListener(window, 'load', initialize);
#map_wrapper {
    height: 400px;
}

#map_canvas {
    width: 100%;
    height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<div id="map_wrapper">
        <div id="map_canvas" class="mapping"></div>
</div>

Plunker

关于javascript - 如何在 Ajax 调用后使用标记渲染 Google map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33945937/

相关文章:

android - Google map 或地点 : API to fetch bulk uploaded (and verified) locations

MouseOver 上的 JavaScript 改变 BODY 样式。在 MouseOut 上反转

javascript - Jquery Datatables - 使整行成为一个链接

jquery - 为什么当我将 div 的这一点 CSS 样式的高度从 px 更改为 % 它不起作用?

javascript - JavaScript 中的日期不相等

javascript - Google map API 的单击并按住事件

javascript - 在哪里可以找到 JavaScript DOM 类层次结构的完整描述?

javascript - 使用 Javascript 在新窗口中打开 PDF 流

javascript - 2 使用相同的选项进行选择,在第一次选择时已选择时发出警报

javascript - WordPress 页面上的谷歌地图插件未显示