Google Maps API Geolocation Text Search Place Details - javascript

I am using google maps api geolocation to get the users location via latlng, then using this location to text search for 'golf' locations around that area. Now I would like to advance from this basic map/markers view to provide place details when the user clicks on the specific map marker. The issue is when I click marker there is no response. I feel like I am one variable off but could really use some help identifying why the details & infowindo fail to appear on click?
I also saw that google is using placeID's to return details? but was unsure if that applied to the maps API detail request.
Thank you in advance for any help.
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: 'golf'
};
infowindow = new google.maps.InfoWindow();
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].geometry.location);
}
}
}
function createMarker(position) {
new google.maps.Marker({
position: position,
map: map
});
}
var request = { reference: position.reference };
service.getDetails(request, function(details, status) {
marker.addListener(marker, 'click', function() {
infowindow.setContent(details.name);
infowindow.open(map, this);
});
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
html, body, #mapcanvas {
height: 400px;
width: 400px;
margin: 0px;
padding: 0px
}
<article>
<p>Finding your location: <span id="status">checking...</span>
</p>
</article>

I see two likely issues here:
var request = { reference: position.reference };
service.getDetails(request, function(details, status) {
Here position is a LatLng, which doesn't have a reference attribute. So your getDetails call fails.
The callback function you pass to getDetails ignores the status, so you never notice any errors it reports.
Combined, this is why nothing happens.
Fix: pass the whole PlaceResult (i.e. results[i], not results[i].geometry.location) to createMarker, so you can access both the location and the Place ID.
As an aside: using reference is deprecated. Use placeId instead.

Related

Google Maps geocode() loop to place markers

I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>

Show places of category in city with google api

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>

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 Places API

I'm a Javascript newbie and I can't seem to get this script working.
Managed to get the geolocation working but no places markers show when loaded.
Tried a lot of stuff can you guys help me out?
var map;
function initialize() {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = document.getElementById('searchtxt');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var request = {
location: pos,
radius: 1500,
types: ['restaurant']
};
alert('OK -> ' + request); //THIS DOESN'T SHOW. WHY??
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
map.setCenter(options.position);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
} else {
}
}
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);
Even the ALERT doesn't show, but if I put it before the var request statement it does show: "OK -> Undefined".
What's wrong?
Thanks.
getCurrentPosition() gets fired asynchronously. This means that the var pos variable isn't set in this scope. This leaves pos undefined. This throws an error when you attempt to set it in the var options object. This breaks the code and the alert() is never fired.
The alert() works before the object because the erroneous assignment, location: pos, hasn't happened yet.
This error was clearly displayed in the console so I would suggest learning to debug that way.
Here is a question that I asked a'while back that might help you:
how to use/store JSON data after the callback has fired?

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