L'API di Google Maps non fornisce poligoni di contea o altri confini predefiniti di stati o paesi. Quindi il problema principale qui è ottenere i dati del poligono.
Un poligono sulla Google Maps è definito costruendo un array di oggetti LatLng
(supponendo che si sta utilizzando l'API v3):
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)
];
allora si potrebbe utilizzare questa matrice per costruire un oggetto Polygon
:
var bermudaTriangle = new google.maps.Polygon({
paths: bermudaTriangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
E finalmente vederlo sulla mappa chiamando il metodo setMap()
:
bermudaTriangle.setMap(map); // Assuming map is your google.maps.Map object
Se si mantiene un riferimento al vostro Polygon
oggetto, è possibile anche nasconderlo passando null
al metodo setMap()
:
bermudaTriangle.setMap(null);
Pertanto si potrebbe prendere in considerazione la costruzione di un oggetto JavaScript con un nome di proprietà per ogni contea. Ciò consentirà di recuperare gli oggetti poligono dal nome delle contee in O(1) (tempo costante), senza dover ripetere tutta la raccolta. Si consideri il seguente esempio:
// 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...
L'oggetto counties
sarà il nostro archivio di dati. Quando un utente cerca "El Dorado" si può semplicemente mostrare il poligono come segue:
counties['El Dorado'].setMap(map);
Se si mantiene un riferimento alla contea precedente ricerca, è possibile anche chiamare setMap(null)
per nascondere il poligono precedente:
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');
}
Spero che questo ti permetta di andare nella giusta direzione.