[英]Google Maps with counties overlay?
我沒有使用谷歌地圖的經驗,但我想在我的網絡應用程序中嵌入“選擇你的縣”地圖。 我的應用程序僅針對加利福尼亞州,因此它只需要支持一個州,但我找不到任何簡單的方法來執行此操作(無需為所有縣行手動繪制疊加多邊形)。
我以為我很容易就能在某種程度上找到Google上“選擇你的縣”風格界面的例子,但我發現的唯一一件事就是這個 - http://maps.huge.info/county.htm - 和如果我找不到更好的選擇,我傾向於使用他們的API來拉動整個狀態的幾何。
有沒有人有任何經驗或見解幫助使這更容易一點?
Google Maps API不提供縣多邊形或州或國家/地區的任何其他預定義邊框。 因此,這里的主要問題是獲得多邊形數據。
Google Maps API上的多邊形是通過構造LatLng
對象數組來定義的(假設您使用的是v3 API):
var bermudaTriangleCoords = [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.757370),
new google.maps.LatLng(25.774252, -80.190262)
];
然后,您將使用此數組來構造Polygon
對象:
var bermudaTriangle = new google.maps.Polygon({
paths: bermudaTriangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
最后通過調用setMap()
方法在地圖上顯示它:
bermudaTriangle.setMap(map); // Assuming map is your google.maps.Map object
如果保留對Polygon
對象的引用,還可以通過將null
傳遞給setMap()
方法來隱藏它:
bermudaTriangle.setMap(null);
因此,您可以考慮使用每個縣的屬性名稱構建JavaScript對象。 這將允許您從O(1)中的縣名(常量時間)中獲取多邊形對象,而無需遍歷所有集合。 請考慮以下示例:
// Let's start with an empty object:
var counties = {
};
// Now let's add a county polygon:
counties['Alameda'] = new google.maps.Polygon({
paths: [
// This is not real data:
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.757370),
new google.maps.LatLng(25.774252, -80.190262)
// ...
],
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.3
});
// Next county:
counties['Alpine'] = new google.maps.Polygon({
// Same stuff
});
// And so on...
counties
對象將是我們的數據存儲。 當用戶搜索“El Dorado”時,您只需按如下方式顯示多邊形:
counties['El Dorado'].setMap(map);
如果保留對先前搜索的縣的引用,還可以調用setMap(null)
來隱藏前一個多邊形:
var userInput = 'El Dorado';
var latestSearch = null;
// Check if the county exists in our data store:
if (counties.hasOwnProperty(userInput)) {
// It does - So hide the previous polygon if there was one:
if (latestSearch) {
latestSearch.setMap(null);
}
// Show the polygon for the searched county:
latestSearch = counties[userInput].setMap(map);
}
else {
alert('Error: The ' + userInput + ' county was not found');
}
我希望這能讓你朝着正確的方向前進。
Google Fusion Tables現在可以鏈接到美國各州的州,郡和國會區數據 。
融合表的幾何字段包含給定對象的Polygon元素。 他們的狀態邊界多邊形(以及較小程度上的縣)在一些地方看起來有點低分辨率,但它可能對你來說足夠好並且應該相對容易抓住。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.