Show places of category in city with google api - javascript

Input: user will select city and place category.
Output: google map with all places that have same category in that city.
How i can do it with google map APIs.
When i try to use places API it’s return json with geographic data but i cant use it with JavaScript or jQuery Json request.
$.getJSON( "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&keyword=cruise&key=YOUR_API_KEY", function( json ) {
console.log( "JSON Data: " + json );
});
But browser log don’t show any output.
Any example code for best way to implement my idea??!
Thank you

You're probably looking for the client-side Places Library's Nearby Search service. Take a look at this working jsfiddle.
JS code below:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
type: ['restaurant']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Hope this helps!

with this code you need only to provide city name and place types or that you can find here:
https://developers.google.com/places/web-service/supported_types
output will show 20 places in same city with type that you passed.
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
var map;
var service;
var infowindow;
var city;
function initMap() {
var cityName = document.getElementById('cityInput').value; // text input html tag
var type = document.getElementById('subCategory').value; // select input html tag
map = new google.maps.Map(document.getElementById('map'), {zoom: 14});
var cityRequest = {
query: cityName,
fields: ['name', 'geometry'],
};
//alert("find!! : " + cityName);
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(cityRequest, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
let city = results[0].geometry.location;
map.setCenter(city);
infowindow = new google.maps.InfoWindow();
//alert(type);
var request = {
location: city,
radius: '1000',
query: type
};
//radius is size of search area
service.textSearch(request, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) { // adding places to map
createMarker(results[i]);
}
//map.setCenter(results[0].geometry.location);
}
});
}
});
}
function createMarker(place) {
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);
});
}
</script>
With this code you will show map in you web page
<div id="map" style="height: 500px; "></div>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap&language=ar" async defer></script>

Related

Is it possible for Google Places API to return one single object instead of an array of objects when querying?

I'm playing around with Google Places API and I was wondering if it were possible to return just one closest result. In the example below I can return all the gyms within a 1km radius which is fine, but if I were to return the closest police station or hospital something for which I'd only want to know the closest one is there a way to do this. It seems the API is returning all the objects within a radius and it can't be altered. I can't seem to find any documentation that highlights this issue, and any attempts I've made still returns all the places in the area.
function GymReport(){
// Gets the latitude and longitude of a location searched by a user
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
var Lat = marker.getPosition().lat();
console.log(Lat);
var Long = marker.getPosition().lng();
console.log(Long);
var location = {lat: Lat, lng: Long};
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: location,
radius: 1000,
type: ['gym']
}, callback);
}
Callback Class
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
if(marker)
marker.setMap(null)
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);<-- This calls the function that will create the markers for the array of results from the API.
}
}
}
Please note that you can order results of Places nearby search by Prominence or by Distance. By default it is ordered by prominence. You can use the rankBy parameter in your code to order by Distance:
rankBy - Specifies the ranking method to use when returning results. Defaults to PROMINENCE. Note that when rankBy is set to DISTANCE, you must specify a location but you cannot specify a radius or bounds.
source: https://developers.google.com/maps/documentation/javascript/3.exp/reference#PlaceSearchRequest
Once you get results ordered by distance just get the first element from array which is the nearest place. Have a look at my sample code
var map;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
rankBy: google.maps.places.RankBy.DISTANCE,
type: ['gym']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
//Get the first result, it's the closest one
createMarker(results[0]);
}
}
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%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=places&callback=initMap" async defer></script>
I hope this helps!

Javascript Google Maps Api, multiple markers with links, only geoceder

I've got problems to put links on multiple markers, I can show my markers on the map, but when a I try tu put link on them, I have always the same link on all markers, the last. Here I provide a sample code:
<div id="map" style="height: 400px; width:100%;"></div>
<script>
var markers = [{"name":"Vasto","url":"http://www.google.com"},{"name":"Chieti","url":"http://www.wikipedia.com"}];
var geocoder;
var map;
var LatLng;
var url;
console.log(markers);
function initMap() {
LatLng = {lat: 42.2872297, lng: 13.3403448};
map = new google.maps.Map(document.getElementById('map'), {zoom: 8, center: LatLng});
geocoder = new google.maps.Geocoder();
setMarkers();
}
function setMarkers() {
var marker, i, url;
for( i = 0; i < markers.length; i++ ) {
url = markers[i].url;
geocoder.geocode({'address': markers[i].name}, function(results, status) {
if (status === 'OK') {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap" async defer></script>
Any solutions?
Thanks in advance
Due to asynchronous code, you need to change your code a bit
function setMarkers() {
markers.forEach(function(item) {
var url = item.url;
geocoder.geocode({'address': item.name}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}

Geolocation with Google maps API and Google text Search

I am new to javascript converting from VB. This is my first shot at creating a dynamic google map and am ultimatly trying to generate a google map using the users location and apply a places search for sports stores. Currently my map generates and zooms to my location but does not apply the search results with markers.
here is my code:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<article>
<p>Finding your location: <span id="status">checking...</span></p>
</article>
<script>
function success(position) {
var s = document.querySelector('#status');
if (s.className == 'success') {
// not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
return;
}
s.innerHTML = "found you!";
s.className = 'success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '560px';
document.querySelector('article').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var service;
var infowindow;
var request = {
location: latlng,
radius: '3200',
query: 'sports'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
</script>
I feel like I might be missing some var assignments or not over writing the current map from "map canvas". Has any one created something similar that provide some insight? Any help is greatly appreciated to find why my search results will not display on the map. Thanks!
Your code works but you are missing the createMarker function. This is not an API method.
Uncaught ReferenceError: createMarker is not defined
An example createMarker function:
function createMarker(place) {
new google.maps.Marker({
position: place.geometry.location,
map: map
});
}
Note: if you only need the location in that function you could also call it and modify it this way:
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
console.log(place);
createMarker(results[i].geometry.location); // pass only the location to createMarker
}
}
}
function createMarker(position) {
new google.maps.Marker({
position: position,
map: map
});
}
JSFiddle demo

Google Maps API Places Search get number of search results

I have implemented a sample using Places Search of Google Maps API. I would like to fetch the number of results I am fetching. New to Google Maps API. How do I achieve this?
jsFiddle
JS:
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(19.107567, 72.8335);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['hospital']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
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);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Replace your callback with this:
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// Just count the number of results passed to your callback
var numResults = results.length;
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}

How do I get more results from Google Places / Maps

I am using google maps and I am trying out places API, but something makes me wonder...
If you load maps.google.com and go to Kuala Lumpur, then type "food" in the search-box, you will see hundreds of restaurants on the map. I would like to get these into my own maps.
Using the Places API, I have pretty much copied their example code:
function initialize() {
var plat = 3.15;
var plong = 101.7;
var ppos = new google.maps.LatLng(plat, plong);
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable: false,
zoom: 10,
center: ppos
};
map = new google.maps.Map(document.getElementById("mapcanvas"), mapOptions);
var request = {
location: ppos,
radius: '10000'
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
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,
icon: place.icon
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent("<b>" + place.name + "</b><br/>" + place.vicinity);
infowindow.open(map, this);
});
}
When I execute this code, I do get results, but only very few and only major locations like a few malls and museums. So, How do I get all that beautiful data, that I see on Google's own map?
So it turned out there were a number of problems:
Categorization is broken in Inodesia, so using keyword instead solved the problem, as in:
var request= {
location: ppos,
radius: 10000,
keyword: 'restaurant' }
keyword takes a string rather than an array, and radius takes a number rather than a string. You can see a summary of the types for the request here: http://code.google.com/apis/maps/documentation/javascript/reference.html#PlaceSearchRequest

Categories

Resources