2016-02-10 27 views
1

我使用谷歌地图API V3的“X”和得到这个错误,而使用遗漏的类型错误:无法读取属性未定义common.js

map.fitBounds(范围);功能

这里是控制台 enter image description here

,这里的错误快照是代码:

var arr = [{lat: -25.363, lng: 131.044}, {lat: 12.97, lng: 77.59}]; 
for (i = 0; i < arr.length; i++) { 
    bounds.extend(new google.maps.LatLng(arr[i])); 
} 
map.fitBounds(bounds); //If I comment this line in m code, the error is gone but map does not load. 

是什么问题?我又该如何解决它?

+1

显示您的全部代码 –

+0

请参阅代码现在.. – Gora

+0

是onload方法中的代码? –

回答

0

google.maps.LatLngBounds.extend方法不会将google.maps.LatLngLiteral对象作为参数(尚)。

extend(point:LatLng) | Return Value: LatLngBounds

Extends this bounds to contain the given point.

将它们翻译成google.maps.LatLng对象。

var bounds = new google.maps.LatLngBounds(); 
var arr = [{lat: -25.363,lng: 131.044}, {lat: 12.97,lng: 77.59}]; 
for (i = 0; i < arr.length; i++) { 
    bounds.extend(new google.maps.LatLng(arr[i].lat, arr[i].lng)); 
} 
map.fitBounds(bounds); 

proof of concept fiddle

代码片段:

function initialize() { 
 
    var map = new google.maps.Map(
 
    document.getElementById("map_canvas"), { 
 
     center: new google.maps.LatLng(37.4419, -122.1419), 
 
     zoom: 13, 
 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
 
    }); 
 
    var bounds = new google.maps.LatLngBounds(); 
 
    var arr = [{lat: -25.363,lng: 131.044}, {lat: 12.97,lng: 77.59}]; 
 
    for (i = 0; i < arr.length; i++) { 
 
    var marker = new google.maps.Marker({ 
 
     position: arr[i], 
 
     map: map 
 
    }); 
 
    bounds.extend(new google.maps.LatLng(arr[i].lat, arr[i].lng)); 
 
    } 
 
    map.fitBounds(bounds); 
 
} 
 
google.maps.event.addDomListener(window, "load", initialize);
html, 
 
body, 
 
#map_canvas { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0px; 
 
    padding: 0px 
 
}
<script src="https://maps.googleapis.com/maps/api/js"></script> 
 
<div id="map_canvas"></div>

+0

谢谢你的小提琴。一个完美的解决方案不起作用。 – Gora

+0

你有同样的错误?请提供[最小,完整,测试和可读示例](http:// stackoverflow。com/help/mcve),在你的问题中展示了这个问题。 – geocodezip

+0

是的,我有同样的错误。你提供的小提琴是我使用的完美代码。你能提出什么可以成为问题吗? – Gora

10

我的猜测是某处在你的代码中有一个self = this没有在它前面一个var声明。

当您忘记var时,您正在创建一个全局变量 - 或者在本例中,将全局self重新定义为您的本地函数。这将导致其预计谷歌地图代码self打嗝是Window并导致Uncaught TypeError: Cannot read property 'x' of undefined(…)

这种错误就是为什么一些开发商喜欢用that或其他一些术语,而不是self的控制范围。如果你是一位超级谨慎的编码人员,并且永远不会忘记你的声明,那么你会好起来的。但对于我们中的那些人谁偶尔会陷入困境,利用that可以节省令人沮丧的调试时间。*

*   那些超级小心程序员会说,我们应得令人沮丧调试的时间,因为我们是不小心 :)

+0

在我的情况下,transpiler为我做了'self = this'(使用ecma6)。这个答案确实节省了我的一天,谢谢。 – Daniele

+2

如果你对谁是那个“自我”感到困惑,只需在错误中放入一个缺点并在chrome控制台中输入“self”即可。 –

+0

男人!你刚刚救了我的一天!谢谢! –

相关问题