Reputation: 13
I'm using this resource guide to establish a dynamic map location default based on the user's IP address: https://developers.google.com/maps/documentation/javascript/geolocation
What I'd also like to do is pass search terms into this API query so that it produces results for "nail salon".
I'm not sure how to do this. Does anyone have any suggestions?
Upvotes: 0
Views: 405
Reputation: 1542
In your case, I would suggest using Google Places API. It can be easily implemented with different kinds of applications. But right now, we'll use it for a web application and we are going to use Places JavaScript Library.
First, create a simple map. You can just copy the code here. Just make sure to use your own API key. To learn more on how to create a simple map, you can check Getting Started.
On the script that loads the Maps Javascript API, add "libraries=places".
Libraries are modules of code that provide additional functionality to the main Maps JavaScript API but are not loaded unless you specifically request them.
To learn more about Places Library, you can check this link. Your script now looks something like this:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
We need to get your current location, so we'll be using Geolcation.
Geolocation is an HTML5 feature, that displays the geographic location of a user or device on a Google map.
Below is the code for geolocation. What it does is to check if HTML5 Geolocation is true. If so, we'll use getCurrentPosition to acquire the user's current coordinates for later use.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// add your map and Places API here.
});
} else {
// Browser doesn't support Geolocation
}
}
getCurrentPosition is a method that accepts an argument(s). The argument returns an object that has cool properties like: latitude, longitude. These properties will play an important role for creating our map and for our Places API. The ideal thing to do is to create a variable object and then use it for the acquired coordinates. Something like this:
var coordinatesObj = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
And then use it to 'center' property for our map.
map = new google.maps.Map(document.getElementById('map'), {
center: coordinatesObj,
zoom: 14
});
Create a variable 'service'. In this variable, we'll create a new instance of PlacesService. This object accepts an argument, which is the map ID.
var service = new google.maps.places.PlacesService(map);
With Place service, you can perform four kinds of searches:
In your case, Nearby Search seems to be the best choice.
A Nearby Search lets you search for places within a specified area by keyword or type.
A Places Nearby search is initiated with a call to the PlacesService's nearbySearch() method, which will return an array of PlaceResult objects.
service.nearbySearch({
location: , // place the coordinates here
radius: 500,
type: ['beauty_salon']
}, callback);
On the 'location' property, use the coordinates that we acquired from the Geolocations's getCurrentPosition method.
service.nearbySearch({
location: coordinatesObj,
radius: 500,
type: ['beauty_salon']
}, callback);
Just be aware that when using 'location', you need to add a 'radius' property and supply a number from 500 to 50000 meters. To learn more, checking this documentation would be very helpful.
You must also pass a callback method to nearbySearch(), to handle the results object and google.maps.places.PlacesServiceStatus response.
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
This callback function adds a marker when the 'status' is google.maps.places.PlacesServiceStatus.OK. In other words, if the status is successful.
You will also notice createMarker() function. This function accepts an argument and creates a marker on every location returned.
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
You will also notice this google.maps.event.addListener
. It responds to user events such as mouse or keyboard events with the map.
These events may look like standard DOM events, but they are actually part of the Maps JavaScript API. Because different browsers implement different DOM event models, the Maps JavaScript API provides these mechanisms to listen for and respond to DOM events without needing to handle the various cross-browser peculiarities. These events also typically pass arguments within the event noting some UI state (such as the mouse position). To learn more, you can check Events.
One more thing, currently, we don't have type 'nail_salon'. So that's why we used 'beauty_salon' in the type property. For the list of supported types, you can check Place Types to learn more.
Bonus stuff:
An InfoWindow displays content (usually text or images) in a popup window above the map, at a given location. The info window has a content area and a tapered stem. The tip of the stem is attached to a specified location on the map.
var infowindow = new google.maps.InfoWindow();
Whole code below:
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infowindow;
function initMap() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var coordinatesObj = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'), {
center: coordinatesObj,
zoom: 14
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: coordinatesObj,
radius: 500,
type: ['beauty_salon']
}, callback);
});
} else {
// Browser doesn't support Geolocation
}
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&libraries=places&callback=initMap">
</script>
And that's it!
Hope this helps and happy coding!
Upvotes: 1