The Google Maps API does not provide county polygons, or any other predefined borders of states or countries. Therefore the main issue here is obtaining the polygon data.
A polygon on the Google Maps API is defined by constructing an array of LatLng
objects (assuming you're using the 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)
];
Then you would use this array to construct a Polygon
object:
var bermudaTriangle = new google.maps.Polygon({
paths: bermudaTriangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
And finally show it on the map by calling the setMap()
method:
bermudaTriangle.setMap(map); // Assuming map is your google.maps.Map object
If you keep a reference to your Polygon
object, you can also hide it by passing null
to the setMap()
method:
bermudaTriangle.setMap(null);
Therefore you could consider building a JavaScript object with a property name for each county. This will allow you to fetch the polygon objects from the name of the counties in O(1) (constant time), without having to iterate through all the collection. Consider the following example:
// 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...
The counties
object will be our data store. When a user searches for "El Dorado" you can simply show the polygon as follows:
counties['El Dorado'].setMap(map);
If you keep a reference to the previously searched county, you can also call setMap(null)
to hide the previous polygon:
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');
}
I hope this gets you going in the right direction.