I successfully set up Google Places for indicating places in a specific town. My only problem: I have not yet achieved to alert the user if he has selected a place which is not in a specific defined town.
I have set up a jsfiddle here: http://jsfiddle.net/pbq2b/
My JS code:
$(function(){
var lat = 51.5073509,
lng = -0.12775829999998223,
latlng = new google.maps.LatLng(lat, lng),
image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
// get town of selected place
function getTown(address_components) {
var geocoder = new google.maps.Geocoder(); result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
var town = getTown(place.address_components);
// if place is in London, move marker to the place
if (town == 'London') {
infowindow.close();
var place = autocomplete.getPlace();
console.log(place);
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
moveMarker(place.name, place.geometry.location);
} else {
// if not, do nothing and alert user
alert('you must click on a place in London');
}
});
function moveMarker(placeName, latlng){
marker.setIcon(image);
marker.setPosition(latlng);
infowindow.setContent(placeName);
infowindow.open(map, marker);
}
});
When you enter a street name such as "Norris Street" the script succesfully recognizes that the place is in London. When you click on a place which is located outside London, also the script successfully recognizes this and alerts the user.
However, if you click on certain sights or train stations such as "Big Ben" or "Heathrow Airport" which obviously are located in London, the script sends out the alert that these places are not in London. How come? How can I achieve that also the city of these places is recognized?
I have the same problem with other cities with this script - with streets no problem, but when I click on a train station for example, the city is not recognized.
Anyone knows a good solution how to identify the city for ALL places?