2017-05-05 79 views
1

我已經閱讀了谷歌地圖API計算距離的一些問題,但仍然不適合我。這裏是我的代碼:谷歌地圖 - computeDistanceBetween無法正常工作

function initMap() { 
    var loc1 = new google.maps.LatLng(37.772323, -122.214897); 
    var loc2 = new google.maps.LatLng(34.1633766,-81.6487862); 

    console.log(google.maps.geometry.spherical.computeDistanceBetween(loc1,loc2)); 
} 

這是我如何調用庫:

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=MY_KEY&libraries=places&callback=initMap" async defer></script> 

但我仍然得到錯誤:未捕獲的類型錯誤:在initMap

無法讀取屬性未定義 「球形」我做錯了什麼?我必須啓用一些自定義API嗎?

回答

6

你在你的src url中有'libraries'參數兩次。

刪除第二個: &庫=地方

...並保持第一位: &庫=幾何,則以

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=MY_KEY&callback=initMap" async defer></script> 
+0

哎喲我白癡...謝謝! – general666

+1

沒問題。有時候只需要一雙新鮮的眼睛。 –

2

沒有與請求的URL的一個問題,參數重複。

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=MY_KEY&callback=initMap" async defer></script> 

爲了使用球形類,你必須包括「幾何」到請求庫列表 - 檢查documentation

// This example requires the Geometry library. Include the libraries=geometry 
// parameter when you first load the API. For example: 
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">