Google Maps Places API - javascript

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?

Related

Google Maps API Geolocation Text Search Place Details

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.

Google Places API not working with getCurrentPosition Geolocation in Ionic app

Trying to get Google Places API to notice my location and apply the functions below. Very new to this and not sure what I am doing wrong below as the API and all the functions works initially, but after I'm asked for my location, it shows where I am but nothing else works/aren't working together.
Cordova Geolocation plugin I added to my ionic app:
cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git
App.js
app.controller("MapController", function($scope, $ionicLoading) {
var map;
var infowindow;
var request;
var service;
var markers = [];
google.maps.event.addDomListener(window, 'load', function() {
var center = new google.maps.LatLng(42.3625441, -71.0864435);
var mapOptions = {
center:center,
zoom:16
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
navigator.geolocation.getCurrentPosition(function(pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
});
$scope.map = map;
request = {
location: center,
radius: 1650,
types: ['bakery', 'bar']
};
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);
});
}
});
});
When you get the position, you update the map's location, but you don't run a new Nearby Search.
So I think you want to call service.nearbySearch(...) in the getCurrentPosition callback.
You may also want to have your nearbySearch callback keep an array of the markers created via createMarker, so you can remove them when you run a new search (e.g. by calling marker.setMap(null) on each old marker).

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 with Geolocation and Places Search

I'm using the Google Maps and places API. I'm trying to have the map show current location WITH surrounding restaurants, cafes, and bars. At this point the map loads and the geolocation is working. I can't seem to get the place markers to show up. I have no idea what I'm missing as I'm learning javascript as quickly as possible.
Any help would be very much appreciated. Thank You!
Here is my current code:
<script>
var map;
var service;
var marker;
var pos;
var infowindow;
function initialize()
{
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
panControl: false,
streetViewControl: false,
mapTypeControl: false,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//HTML5 geolocation
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
infowindow = new google.maps.InfoWindow({map: map,position: pos,content: 'You Are Here'});
var request = {location:pos,radius:500,types: ['restaurant, cafe, bars']};
map.setCenter(pos);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
},
function()
{
handleNoGeolocation(true);
});
}
else
{
handleNoGeolocation(false);
}
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);
</script>
Check that your script call to the Google API includes a reference to the places library. For example:
<script src="http://maps.googleapis.com/maps/api/js?key=yourAPIkey&libraries=geometry,places&sensor=true&language=en"></script>
In this line of code:
var request = {location:pos,radius:500,types: ['restaurant, cafe, bars']};
instead of types: write keyword:

callback function not working

I've created a script that places a marker on a map based on the area you click your mouse over. Once that marker is placed, when your mouse hovers over the marker, an infobox should appear with the address of where the marker is placed. However, the infobox isn't showing up because when I call "info_text", it returns undefined. I realized that I needed to add in a callback function but I don't think I'm implementing it correctly. Could anyone help me fix my code? Thanks
My code:
var geocoder;
function initialize()
{
geocoder = new google.maps.Geocoder();
var event = google.maps.event.addListener;
// intializing and creating the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
event(map,'click',function(e){
var marker = placeMarker_and_attachMessage(e.latLng,map,count);
count = count + 1;
});
} // end of initalize.
function placeMarker_and_attachMessage(position,map)
{
var event = google.maps.event.addListener;
var message = ['This', 'is', 'the', 'secret', 'message'];
var marker = new google.maps.Marker({
position: position,
map: map
});
var pos = info_text(position);
alert('pos is: ' + pos);
var infowindow = new google.maps.InfoWindow({
content: 'hello'
});
event(marker,'mouseover',function(){
infowindow.open(map,this);
});
event(marker,'mouseout',function(){
infowindow.close();
});
} // end of function.
function info_text(position)
{
var lat = parseFloat(position.lat());
var lng = parseFloat(position.lng());
alert('lat,lng is: ' + (lat,lng));
var latlng = new google.maps.LatLng(lat,lng);
alert('just before geocode');
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
alert('in info_text If statement');
if(results[1])
{
alert('in inner if statement');
var finalResult = myCallback(results[1].formatted_address);
return finalResult;
}
else
{
alert('no results found');
}
}
else
{
alert('could not pinpoint location');
}
});
}
function myCallback(loc)
{
alert('i have a location!');
return loc;
}
google.maps.event.addDomListener(window, 'load', initialize);
Your function info_text doesn't return anything, so this line:
var pos = info_text(position);
is where pos is undefined.
You need to include:
return something;
at some point in your function (like you have done further down).
Added
Your function myCallback returns a value, but where it is used:
myCallback(results[1].formatted_address);
it doesn't store the return-value anywhere - it is just discarded.

Categories

Resources