I’ve just started playing with the Google Maps Javascript API for a web version of Hpflsk. So far so good, but there are a few little quirks that have left me a bit baffled. I’ve also thrown in some examples that fit our use case.
Include the Libraries You Need
Firstly, if you jump directly into the API Reference, wherever you see the word library after the heading in the table of contents, e.g. Places Library, you need to make sure you load that library when you load the API.
https://maps.googleapis.com/maps/api/js?key=XXXXXXX&sensor=false&libraries=places
I spend way too long in the javascript console writing google.maps.pl… and hitting the tab key and couldn’t work out why places was missing!
Geocoding versus Places Search
Geocoding is the process of turning an address – e.g. 123 Fake Street – into a geographic point (latitude/longitude). If you want to search for a location by name – e.g. Lucky Donut Shop – similar to what you can do in the search box on Google Maps, you need to use TextSearchRequest in the Places Library. Here’s how I implemented a text search for places near the user’s current location:
// HTML
...
<div id="map-modal-inner"></div>
...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXX&sensor=false&libraries=places"></script>
// JS
// Find the venue location by searching on the venue name
// Get client's location using HTML5 navigator.geolocation
var venueLocation;
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var myLocation = new google.maps.LatLng(latitude, longitude);
// Search for places nearby and take the first result
// First make a temporary map object
var mapOptions = {
center: myLocation,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-modal-inner"), mapOptions);
// Then search for places matching the venue name
var places = new google.maps.places.PlacesService(map);
var placesRequest = {
query: "Lucky Donut Shop",
location: myLocation,
// favour results within 50km of currrent location
radius: '50000'
};
places.textSearch(placesRequest, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// for some reason jb = latitude, kb = longitude
var loc = results[0].geometry.location;
venueLocation = new google.maps.LatLng(
results[0].geometry.location.jb,
results[0].geometry.location.kb);
}
});
});
</script>