2012-04-18 134 views
22

我正在嘗試使用Google地圖查找兩點之間的位置。下面是我的工作代碼:兩個位置之間的距離 - Google地圖

function initialize() { 
      var myOptions = { 
      center: new google.maps.LatLng(36.8813329,-103.6975488), 
      zoom: 4, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
      }; 
      var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions); 

      var impactCoordinates = [ 
       new google.maps.LatLng(37.772323, -122.214897), 
       new google.maps.LatLng(34.1633766,-81.6487862), 
          ]; 
      var ImpactPath = new google.maps.Polyline({ 
       path: impactCoordinates, 
       strokeColor: "#FF0000", 
       strokeOpacity: 1.0, 
       strokeWeight: 2 
      }); 

      ImpactPath.setMap(map); 

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

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

這是我從控制檯得到如下錯誤:

Uncaught TypeError: Cannot read property 'spherical' of undefined

回答

48

如果您還沒有這樣做,明確添加幾何庫在你的<script>標籤 src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false">

+2

謝謝!這正是我所錯過的。 – cclerville 2012-04-18 14:21:05

+0

也有必要使用上面的URL;也就是'http://maps.google.com/maps/api/js?sensor = false&?libraries = geometry'將不起作用。 – Arthur 2014-03-20 00:40:32

+0

@Arthur那是因爲你忘記刪除了問號。 '&?libraries = geometry'應該是'&libraries = geometry' – jimmystormig 2016-02-20 12:42:06