2012-04-27 189 views
0

我想從多個位置對中用Google Maps JavaScript API繪製多個測地多折線。我在這裏找到了98%的東西(http://stackoverflow.com/questions/2994424/google-maps-geocoding-address-to-glatlng),但我無法弄清楚如何添加附加點和另外的線路(也顯示芝加哥,美國和洛杉磯,美國之間的線路)。感謝任何人都可以提供的幫助。谷歌地圖地理編碼多行

回答

3

新的更新,這一個將目標點編碼放入一個單獨的函數,並使每個地理編碼調用獨立。應該比嘗試嵌套回調過程更具可擴展性。

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps API Geocoding Demo</title> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script> 
</head> 
<body> 
    <div id="map" style="width: 1280px; height: 1024px;"></div> 

    <script type="text/javascript"> 
//add locations 
    var map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 2, 
     center: new google.maps.LatLng(35.00, -25.00), 
     mapTypeId: google.maps.MapTypeId.TERRAIN 
    }); 

    var address1 = '60033'; 

    var gc = new google.maps.Geocoder(); 
    gc.geocode({'address': address1}, function (res1, status) { 

     var hub = res1[0].geometry.location; 
     new google.maps.Marker({ 
      position: res1[0].geometry.location, 
      map: map 
      }); 

     geocodeLine(hub, '44145'); 
     geocodeLine(hub, '03103'); 
     geocodeLine(hub, '30236'); 
     geocodeLine(hub, '18106'); 
     geocodeLine(hub, '64147'); 
     geocodeLine(hub, '86401'); 
     geocodeLine(hub, '75110'); 
     geocodeLine(hub, '56001'); 
     geocodeLine(hub, '80239'); 
     geocodeLine(hub, '95776'); 
    }); 

    function geocodeLine(hub, address) 
    { 
     var gc = new google.maps.Geocoder(); 

     gc.geocode({'address': address}, function (res, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 

       new google.maps.Marker({ 
       position: res[0].geometry.location, 
       map: map 
       }); 

       new google.maps.Polyline({ 
       path: [ 
        hub, 
        res[0].geometry.location 
       ], 
       strokeColor: '#FF0000', 
       geodesic: true, 
       map: map 
       }); 
      } 
     }); 
    } 
    </script> 
</body> 
</html> 
+0

非常感謝您的回覆。您發送示例的唯一問題是它正在線性地處理所有地址。有沒有辦法讓他們每個人都是獨一無二的?例如,一條從倫敦到紐約,另一條從芝加哥到洛杉磯。該代碼生成倫敦到紐約,芝加哥到洛杉磯。如果我不想要紐約到芝加哥的腿?再次感謝TON! – 2012-04-30 16:32:04

+0

在這種情況下,您需要創建多條多段線,因爲多段線表示一條連續線條,並且有兩條線,您需要創建兩條多段線。我已經舉了一個例子來展示我在上面的答案中的含義。 – javram 2012-04-30 17:10:34

+0

你是男人!再次感謝所有的幫助。另一個快速問題給你。我已經爲我的需要編寫了這個代碼,但是當我添加太多點時,我似乎碰到了一堵牆。如果您查看http://www.maptest.freehosting.com/chi.html,我製作了我試圖製作的地圖,除了我需要再添加一點。但是當我嘗試添加第12點時,它不起作用。任何想法可能會造成這種情況?它是谷歌的東西,腳本的東西或用戶錯誤(我)?謝謝。 – 2012-04-30 20:23:45