Reputation: 2164
I can't find any articles in Google Maps documentation hope somebody here did or know how to achieve that what I need.
So basically I have array of locations
example of array
const array = [
{
latitude: 37.783476,
longitude: -122.425412,
}
]
Now I need to filter this array based on city (e.g San Francisco).
How can I achieve this?
Any links to documentation or any ideas much appreciated.
Upvotes: 0
Views: 1007
Reputation: 211
You can achieve it using reverse geocoding.
js fiddle: https://jsfiddle.net/fatty/bdartuph/12/
Here i have taken two coordinates in array - san francisco and new york. So the array will get filtered by the city you write in input box and will get store in filteredArray.
var coordArray = [{
latitude: 37.783476,
longitude: -122.425412,
},
{
latitude: 40.730885,
longitude: -73.997383,
}
];
$("#btn").click(function() {
var filteredArray = [];
var cityName = $("#cityName").val();
var geocoder = new google.maps.Geocoder();
for (var i = 0; i < coordArray.length; i++) {
var latlng = new google.maps.LatLng(coordArray[i].latitude, coordArray[i].longitude);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var address = results[0].formatted_address.split(',');
alert("" + address[1]);
if (address[1].toLocaleLowerCase().trim() == cityName.toLocaleLowerCase()) {
filteredArray.push(coordArray[i]);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<input id="cityName" type="text" placeholder="write city name">
<input id="btn" type="button" value="filter coordinates" />
Upvotes: 2