2013-05-16 52 views
0

我有一組自定義位置,並且我有一個網頁。如何映射谷歌地圖上的任意點?

在我的網頁上,我有一個功能正常的Google地圖(使用API​​的v3)。

如果您輸入地址,它將以該地址爲中心。沒什麼好激動

當用戶輸入一個位置時,我希望地圖在他們輸入的位置的某個半徑範圍內包含我的任何自定義位置。

有人可以指向我的API參考做到這一點嗎?我知道這不難,但對於我的生活,我找不到一個好的參考或例子。

回答

0

這竟然用標記是很容易計算出兩點之間的距離。 AddCustomLocationsToMap函數在下面做了真正的工作。感謝this blog post爲起點。

function FocusMapOnAddress(address) { 
    var mapCenter; 
    geocoder.geocode({ 'address': address }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      cdamap.setCenter(results[0].geometry.location); 
      mapCenter = results[0].geometry.location; 
      var marker = new google.maps.Marker({ 
       map: cdamap, 
       position: mapCenter 
      }); 
     } else { 
      alert("Address could not be resolved due to an error: " + status); 
     } 
    }); 

    //if we actually know where they are (i.e., valid address) then zoom and show locations 
    if (mapCenter != null) { 
     AddCustomLocationsToMap(); 
     SetMapZoomLevel(mapCenter, SearchRadiusInMeters()); 
    } 
} 

var locations = [ 
    ['High Park', 43.6516699, -79.4652915, 4,'Our High Park Office is open from 9am - 5pm'], 
    ['King Street CDA Office', 32.775692, -79.932863, 5,'Our King Stret Office is open from 8am - 4pm'], 
    ['Cronulla Beach', -34.028249, 151.157507, 3,''], 
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 2,''], 
    ['Maroubra Beach', -33.950198, 151.259302, 1,''] 
]; 

function AddCustomLocationsToMap() { 
    //show custom locations, pulled from the "locations" array 
    for (i = 0; i < locations.length; i++) { 
     marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
      map: cdamap 
     }); 

     google.maps.event.addListener(marker, 'click', (function (marker, i) { 
      return function() { 
       infowindow.setContent(HTMLForLocation(i)); 
       infowindow.open(cdamap, marker); 
      } 
     })(marker, i)); 
    } 
} 

function HTMLForLocation(idx) { 
    //return HTML for display to the user when they click on the specified location 
    var selectedLocation = locations[idx]; 
    if (selectedLocation != null) { 
     return '<b>' + locations[idx][0] + '</b>' + '<br/>' + locations[idx][4]; 
    } 
    else { 
     return "Unknown location"; 
    } 
} 
+1

你爲什麼不接受你的答案? – alkis

+1

感謝您的提醒 – JosephStyons