Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Erik Nuber
20,629 PointsUsing Places API in Google Maps
I have spent the last couple of days trying to figure out how to accomplish what should be a very simple request with Google Maps.
On the site I am working on, I have a google map. I have it set to geolocate so that whenever someone uses it and agrees to being located this way, the map zooms to where they are...that part is fine and was easy to do.
From there, I am trying to find a way to get the JSON response file from a places search. I would specifically like to get that JSON data and play with it how I want to rather than have it place markers on the map at first. I have built up a URL based on the information I am looking for but, there is no place that explains how to use that URL to get what you want. I have tried using Ajax to send the request but I get a cross origin error.
I have tried using both $.ajax and $.getJSON. Google Maps does not provide JSONP so it must be JSON format.
I just don't get what it is I am missing. I have researched, googled all over the place trying to figure out how to simply get the JSON response back
Here is a link to the page that has what they seem to think is the answer but, I am apparently missing something. If anyone could please help it would be greatly appreciated as maybe it is something obvious that just needs fresh eyes.
Thank You!!!
3 Answers

Erik Nuber
20,629 Pointsvar curLat, curLng, locations, success;
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
"use strict";
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
function initMap() {
"use strict";
var mapOptions = {
zoom: 12,
center: {lat: 33.683947, lng: -117.794694}
},
map = new google.maps.Map(document.getElementById('map'), mapOptions),
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
};
curLat = position.coords.latitude;
curLng = position.coords.longitude;
map.setCenter(pos);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
//bind submit button
var submitClick = document.getElementById('submitButton');
var guess = document.getElementById('guess');
function updateValue() {
"use strict";
guess = guess.value;
console.log(guess);
}
submitClick.addEventListener('click', updateValue);
var accessURL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=33.683947,-117.794694&radius=16093&keyword=starbucks&key=MYAPIKEYISHERE';
$.getJSON({
type: "GET",
// contentType: "applicaton/json; charset=utf-8",
url: accessURL,
dataType: "JSON",
success: function (data) {
"use strict";
$("#map").html(data);
}
});
The accessURL is the URL that I built. If I copy it and paste it into the browser, I get the info I want. I just don't know how to use it to get it into a variable since I can't actually use an ajax call.

Erik Nuber
20,629 PointsAnybody? So frustrating I can only find info from older versions of Google Maps and none of it is relevant any more.

Chyno Deluxe
16,936 PointsIf you'd like to use the JSON data from your api call, for example, grab the icon of the first result, then you would call, data.results[0].icon inside of your success function.
You cannot call data from JSON outside of the $.getJSON() method becuase the call is made asynchronously.
This is just assumption since i am unable to reproduce your environment and test my answer. but that is how you would be able to gain access to json data in a $.getJSON call.
Let me know if you have any more questions.

Erik Nuber
20,629 PointsYou are unable to make that call to Google Maps. This is the issue. There must be another way to access the data but, I have been thru the documentation over and over and outside of their basic examples there is no indication how you make the request. I have tried both $.ajax and $.getJSON() as Google Maps only supports JSON and XML not JSONP. Regardless if I write it out in JS or jQuery I get the same error.
XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=33.68…radius=16093&keyword=starbucks&key=MYKEYISHERE. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:51899' is therefore not allowed access.
Here is there example...
Request
location: -33.8670,151.1957
radius: 500
types: food
name: cruise
key: API_KEY
You can use these to build this example url.
url
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=cruise&key=YOUR_API_KEY111
This is what you would get back but, the outside of copy/pasting the url into a new window and visibly seeing these results, I have yet to be able to get this back into my program.
Response
{
"debug_log" : {
"line" : []
},
"html_attributions" : [],
"logging_info" : {
"experiment_id" : [],
"query_geographic_location" : "AU"
},
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.86879,
"lng" : 151.194217
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
"name" : "Rhythmboat Cruises",
"opening_hours" : {
"open_now" : false,
"weekday_text" : []
},
"photos" : [
{
"height" : 426,
"html_attributions" : [
"\u003ca href=\"https://www.google.com/maps/views/profile/104066891898402903288\"\u003eRhythmboat Cruises\u003c/a\u003e"
],
"photo_reference" : "CmRdAAAA-YL_I ...photo_reference truncated in this example",
"width" : 640
}
],
"place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
"reference" : "CnRmAAAAvQl ...reference truncated in this example",
"scope" : "GOOGLE",
"types" : [ "restaurant", "food", "point_of_interest", "establishment" ],
"vicinity" : "Pyrmont Bay Wharf (Near Australia Maritime Museum), Pyrmont, NSW 2009"
},
{
"geometry" : {
"location" : {
"lat" : -33.867591,
"lng" : 151.201196
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id" : "a97f9fb468bcd26b68a23072a55af82d4b325e0d",
"name" : "Australian Cruise Group",
"opening_hours" : {
"open_now" : false,
"weekday_text" : []
},
"photos" : [
{
"height" : 1331,
"html_attributions" : [
"\u003ca href=\"https://www.google.com/maps/views/profile/110751364053842618118\"\u003eAustralian Cruise Group\u003c/a\u003e"
],
"photo_reference" : "CmRdAAAAtEo ...photo_reference truncated in this example",
"width" : 2000
}
],
"place_id" : "ChIJrTLr-GyuEmsRBfy61i59si0",
"reference" : "CnRqAAAAFbuk ...reference truncated in this example",
"scope" : "GOOGLE",
"types" : [
"restaurant",
"travel_agency",
"food",
"point_of_interest",
"establishment"
],
"vicinity" : "32 The Promenade, King Street Wharf 5, Sydney"
},
{
"geometry" : {
"location" : {
"lat" : -33.870943,
"lng" : 151.190311
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
"id" : "e644f7f34cf875b9919c6548f1b721947362850a",
"name" : "Lunch Cruise with Jazz on Sydney Harbour",
"opening_hours" : {
"open_now" : false,
"weekday_text" : []
},
"photos" : [
{
"height" : 292,
"html_attributions" : [
"\u003ca href=\"https://www.google.com/maps/views/profile/105423912060796272053\"\u003eFrom a Google User\u003c/a\u003e"
],
"photo_reference" : "CmRdAAAAR4bq ...photo_reference truncated in this example",
"width" : 438
}
],
"place_id" : "ChIJLfySpTOuEmsRPCRKrzl8ZEY",
"reference" : "CoQBewAAAFd2 ...reference truncated in this example",
"scope" : "GOOGLE",
"types" : [ "bar", "restaurant", "food", "point_of_interest", "establishment" ],
"vicinity" : "37 Bank St, Pyrmont"
}
],
"status" : "OK"
}
Google Maps does not allow these calls because of cross-domain security issues. I have searched extensively for answers but, all the answers are years old and, no longer apply as there is a newer version of Google Maps that is being used and answers are based on the previous version which is no longer supported.
After spending the last few days trying to figure this out, I am basically giving up. I was doing it for my own purposes to practice and learn but, even as stubborn as I am to figure things out, this is just something I have spent hours and hour without getting anywhere. I have watched plenty of online tutorials for this and, read thru pages and pages of informaiton and am just lost.
Thanks though for answering.

Chyno Deluxe
16,936 PointsAhh. I figured this might be the problem and you've just confirmed my suspicion. The problem is that Google Chrome has deprecated geolocation on NON-HTTPS proxies. So you won't be able to recieve data from Google Maps becuase of this deprecated functionality.
Once you get SSL on your server, you should be able to make the call to Google Maps API.
I hope this helps.
Chyno Deluxe
16,936 PointsChyno Deluxe
16,936 PointsDo you have a url where we can view the code in action to help find the specific problem you are having?