簡體   English   中英

未捕獲的TypeError:無法讀取未定義的common.js的屬性'x'

[英]Uncaught TypeError: Cannot read property 'x' of undefined common.js

我正在使用google map api v3,並在使用時收到此錯誤

map.fitBounds(bounds); 功能

這是控制台上的錯誤快照 在此處輸入圖片說明

這是代碼:

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.

問題是什么? 另外我該怎么解決呢?

我的猜測是,在代碼的某個地方有一個self = this而在它前面沒有var聲明。

當您忘記var您將創建一個全局變量-或在這種情況下,請將全局self定義為局部函數。 這會在Google Maps代碼中引起打which,該代碼期望selfWindow並導致Uncaught TypeError: Cannot read property 'x' of undefined(…)

這種錯誤是為什么某些開發人員更喜歡使用that或其他術語而不是使用self進行范圍控制的原因。 如果您是一個非常小心的編碼器,並且永遠不要忘記您的var聲明,那將會很好。 但是對於那些偶爾搞砸的人來說,使用that可以節省數小時令人沮喪的調試工作。*

* 那些非常謹慎的編碼人員會說,我們值得花時間進行令人沮喪的調試,因為我們很粗心 :)

google.maps.LatLngBounds.extend方法未將google.maps.LatLngLiteral對象作為參數(尚未)。

擴展(point:LatLng)| 返回值:LatLngBounds

擴展此邊界以包含給定點。

將它們翻譯成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);

概念證明

代碼段:

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM