Google Map API to find nearby restaurant around my place - javascript

I am working on Google map api [Here is my to find out near by restaurant. . . When I run this, I get only current location. I am not receiving any information related to restaurant data.
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 25.276987, lng: 55.296249 },
zoom: 15
});
var infoWindow = new google.maps.InfoWindow({ map: map });
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
var marker = new google.maps.Marker({
map: map,
position: pos.getPlace().location
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: rak,
radius: 5500,
type: ['restaurant'] // not resturant
}, callback);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
}
else {
handleLocationError(false, infoWindow, map.getCenter());
}
}

Maybe you are encountering an error with the nearbySearch location tag. You didn't initiate the variable rak and it will return a null value.
Set the Script
<script
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
async defer></script>
Initialize you variables
var map;
var infowindow;
var myPlace = {lat: 25.276987, lng: 55.296249 };
Call your nearBySearch
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location : myPlace,
radius : 5500,
type : [ 'restaurant' ]
}, callback);
Check the result of search and then create a marker for each found location
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);
});
}
You can find this code in this document, it will explain well the proper coding and how to use the api. Also here is the list of supported location type.
I hope this helps.

Related

How to change Google Maps info window to a geolocation marker

I followed a tutorial by Google https://developers.google.com/maps/documentation/javascript/geolocation so I could display the users position on a map. It currently looks like this with an info window:
However I would like to display a geolocation marker instead of the info window:
Here is my code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.520008, 13.404954)
};
infoWindow = new google.maps.InfoWindow;
map = new google.maps.Map(document.getElementById("map"), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
Any help on how to change it from an info window to geolocation marker would be great. Thanks in advance.
To display location with marker in Google maps, you can try this:
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: 52.520008, lng: 13.404954},
zoom: 8,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(52.520008, 13.404954),
map: map,
/*if you want to custom marker icon, you can set icon path here*/
icon: 'your_icon_url',
/* if you don't want to enable dragging, just remove this property */
draggable: true
});
// if you enable dragging, you can initialize this event
// to get latitude, longitude and address
google.maps.event.addListener(marker, 'dragend', function (marker) {
var latLng = marker.latLng;
var currentLatitude = latLng.lat();
var currentLongitude = latLng.lng();
var geocoder = new google.maps.Geocoder;
var latlng = { lat: currentLatitude, lng: currentLongitude };
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
// address
console.log(results);
} else {
console.log('Geocoder failed due to: ' + status);
}
});
});
Note: To work with places in Google maps, you need to require libraries=places as a parameter inside the url:
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places
Reference: For more marker icons designed by Google, you can refer here: What are the filenames of new colored Google maps markers?

Use Reverse Geocoding in Vue.js

I'm working on a project which track GPS locations and should display in Google map as points. Therefore I use Reverse Geocoding.
I just put below code inside methods: in my Component.
initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 40.731, lng: -73.997}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
document.getElementById('submit').addEventListener('click', function() {
this.geocodeLatLng(geocoder, map, infowindow);
});
},
geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
Also I put below code in app.blade.php
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap">
</script>
My problem is when I use callback in parameter the initMap function is not identified. Therefore map is not loading on my view. How should I use it? and also should I need to use axios.get(my_url_here) to do this? I'm stuck in this case. If anyone can consider and help me for this matter would be grateful.

Getting nearby places to the device current location using google places api on javascript

I'm using Google maps API and Google Places API to get the user's device current location and to retrieve the nearby restaurants, gyms, etc. from that location. I've checked the official google documentation and I've created this code:
html code:
<div id="map"> </div>
<script src="https://maps.googleapis.com/maps/api/js?key=I_REPLACED_MY_KEY_IN_HERE&libraries=places&callback=initMap" async defer ></script>
JAVASCRIPT:
var map;
var service;
var infowindow;
var pos;
var request;
var place;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
getLocation();
getNearByPlaces();
callback();
}
function getLocation(){
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
infowindow = new google.maps.InfoWindow();
}
function getNearByPlaces(){
request = {
location: pos,
radius: '500',
query: 'restaurant'
};
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++){
place = results[i];
}
}
}
I'm getting the map with the nearby places and the device current location, the problem is that I'm not getting only the restaurants as I specified in my request, I want to get restaurants only in 500 radius and to retrieve their latitudes and longitudes, getnearbyplaces and callback aren't doing anything.
The geolocation service is asynchronous. You need to call getNearByPlaces when the location is available, in the callback function for the geolocation service.
function getLocation() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
getNearByPlaces(pos); // depends on value of pos
// existing error handling...
proof of concept fiddle
code snippet:
var map;
var service;
var infowindow;
var pos;
var request;
var place;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
getLocation();
// getNearByPlaces();
// callback();
}
function getLocation() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log("getLocation:" + pos.lat + "," + pos.lng);
var marker = new google.maps.Marker({
position: pos,
map: map,
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
})
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
getNearByPlaces(pos);
}, function() {
console.log("calling handleLocationError(true)");
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
console.log("calling handleLocationError(false)")
handleLocationError(false, infoWindow, map.getCenter());
}
infowindow = new google.maps.InfoWindow();
}
function getNearByPlaces(pos) {
console.log("getNearByPlaces:" + pos.lat + "," + pos.lng);
request = {
location: pos,
radius: '500',
query: 'restaurant'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log("callback received " + results.length + " results");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < results.length; i++) {
console.log(JSON.stringify(results[i]));
place = results[i];
var mark = createMarker(results[i]);
bounds.extend(mark.getPosition());
}
map.fitBounds(bounds);
} else console.log("callback.status=" + status);
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: "http://maps.google.com/mapfiles/ms/micons/red.png"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
return marker;
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

Bring in Google maps 'infowindow' information for current location

I am using the Google Maps Javascript API. The sample code; I think gets me close but doesn't accomplish what I hoped for.
I hard code a 'placeid'
I am hoping to bring in my current location instead.
I do bring in my current location in the sample code but the Infowindow information is hard coded.
I am hoping to learn how to bring in both the 'Current Location' marker and 'Infowindow' place information dynamically without the need to hard code it.
My broken script follows>>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 42.0491125,
lng: -92.91123340000001
},
zoom: 12
});
var infowindow = new google.maps.InfoWindow();
// var infoWindow = new google.maps.InfoWindow({map: map});
var service = new google.maps.places.PlacesService(map);
service.getDetails({
// I would like to bring in the current position not a static place id
placeId: 'EioxMDEgRSBNYWluIFN0LCBNYXJzaGFsbHRvd24sIElBIDUwMTU4LCBVU0E'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'lat lng: ' + place.geometry.location + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, this);
});
}
});
var infoWindow = new google.maps.InfoWindow({
map: map
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Home Point.');
map.setCenter(pos);
var marker = new google.maps.Marker({
title: 'Your current location',
map: map,
// title: 'Your current location'
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&libraries=places&callback=initMap">
</script>
</body>
</html>
You could combine Geolocation service to determine the current location and then Reverse Geocoding to resolve address information (inc. place id) as demonstrated below
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 42.0491125, lng: -92.91123340000001 },
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({ map: map });
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
resolvePlace(pos,
function (place) {
var marker = new google.maps.Marker({
title: place.formatted_address,
map: map,
position: pos
});
//infoWindow.setPosition(pos);
infoWindow.setContent(place.formatted_address);
map.setCenter(pos);
infoWindow.open(map,marker);
},
function (status) {
infoWindow.setPosition(pos);
infoWindow.setContent('Geocoder failed due to: ' + status);
});
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function resolvePlace(pos, success, error) {
var geocoder = new google.maps.Geocoder;
geocoder.geocode({ 'location': pos }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
success(results[0]);
} else {
error('No results found');
}
} else {
error(status);
}
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap">
</script>
Plunker

Google Maps - get address of the current map position

I'm building a website that uses Google Maps. There is a div conatinint the map that can be moved about with the pointer.
I need to get the nearest street address of the currently centred view in the map. How do I do it?
Thanks
According to gmap geocoding, you can find the json array of coordinate by directly pass it to url, for example
location: lat:40.714224, lng:-73.961452
Use Google Map's GeoCoding:
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 40.731, lng: -73.997}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
document.getElementById('submit').addEventListener('click', function() {
geocodeLatLng(geocoder, map, infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}

Categories

Resources