Google 地图 API 无法在移动浏览器上使用

Google Maps API won't work on mobile browser

我在我的网站上使用 Google 地图 API 自定义标记,它在桌面浏览器中运行良好,但不会出现在移动浏览器中。我的控制台出现错误: TypeError: Cannot read property 'length' of undefined.

我使用 ajax 获取数据。这是 javascript:

var myLatlng = new google.maps.LatLng(-0.7893, 113.9213);
var mapOptions = {
    zoom: 4,
    center: myLatlng,
    scrollwheel: false, 
    mapTypeControl: false,
    styles: []
};

var locations = response;

var map = new google.maps.Map(document.getElementById("map"), mapOptions);

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));
}

如有任何帮助,我们将不胜感激。

解决了向#map 添加固定高度(之前为 100%)的问题。

检查 "locations.length" 是否存在,如果不存在它将 return 为 null 并且长度值会出错。你可以这样做 -

if (!locations ==0){
for (var i = 0; i < locations.length; i++)
....

您可以找到更多答案Uncaught TypeError: Cannot read property 'length' of null