Errors and Trouble Working with Google Maps API

Errors and Trouble Working with Google Maps API
0.0 0

#1

I’'m enrolled with Thinkful, working on my Front-End Capstone, and am having lots of trouble. I am attempting to use Google Maps API to get Details and Places for a local restaurant search web app. I feel like I’ve exhausted all other efforts (Slack channels, mentor, Q&A sessions with Thinkful, Google, etc.)

First of all, here’s my repo. The up-to-date branch is ‘errors’ branch, while the master has no issues (other than maybe I’m doing something fundamentally wrong in my code that I don’t know about).

Errors:

GET https://maps.googleapis.com/maps/api/place/findplacefromtext/json?&key=AIzaSyCT4F67piVv6cvASPssAR1s_buPw6kBQw0&query=vegan 500 ()

/Users/DavidDoes/Documents/projects/veghead/index.html?#resources:1 Failed to load https://maps.googleapis.com/maps/api/place/findplacefromtext/json?&key=AIzaSyCT4F67piVv6cvASPssAR1s_buPw6kBQw0&query=vegan: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 500.

Someone linked me to this post on Stack Overflow, but I’m not sure how to implement that in my situation.

General issues:

  • How can I access the API once I’ve “captured” it. So once I get these errors out of the way, how can I console.log the objects so I know how to get the information (key:value pairs) that I need?
  • I’m pretty vague on how callback functions work. I know that my button click listener needs to pass the user’s input to a function, and call a function, but it’s pretty fuzzy beyond that.

Thank you all!


#2

where did you get that link? I can’t find it in the google maps docs…

EDIT: nvm, found it
https://developers.google.com/places/web-service/search


#3

so after reading through the docs a bit, i created this url, which doesn’t get results, but also doesn’t throw an error:

https://maps.googleapis.com/maps/api/place/findplacefromtext/json?key=AIzaSyCT4F67piVv6cvASPssAR1s_buPw6kBQw0&input=vegan&inputtype=textquery

so your url was slightly malformed (no & immediately after ?) and also you needed the inputtype parameter

need to read more to figure out why no results are given though…


#4

OK. I think I understand. The docs aren’t very clear, but if you copy and paste their sample urls and play with them, you can see what’s going on.

By the way, you can see the responses for any of these urls by just pasting them into your address bar!

so if you use a url like this:
https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=vegan&inputtype=textquery&key=AIzaSyCT4F67piVv6cvASPssAR1s_buPw6kBQw0

you get no results, probably because its gonna search the whole world for the word vegan and google doesn’t want to send all that data.

if you do this (i have no idea where that circle is, i just copied it from the docs):

https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=vegan&inputtype=textquery&locationbias=circle:2000@47.6918452,-122.2226413&key=AIzaSyCT4F67piVv6cvASPssAR1s_buPw6kBQw0

then you get this (a single result, which is just a place id that you then have to look up in another google api):

{
   "candidates" : [
      {
         "place_id" : "ChIJi5Mg6GMUkFQRz_FTACxLeJs"
      }
   ],
   "debug_log" : {
      "line" : []
   },
   "status" : "OK"
}

but, if you add fields to your url (read here about fields: https://developers.google.com/places/web-service/search#Fields) like this:

https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=vegan&inputtype=textquery&fields=photos,formatted_address,name,opening_hours,rating&locationbias=circle:2000@47.6918452,-122.2226413&key=AIzaSyCT4F67piVv6cvASPssAR1s_buPw6kBQw0

then you get all these goodies:

{
   "candidates" : [
      {
         "formatted_address" : "801 NE 65th St, Seattle, WA 98115, USA",
         "name" : "Wayward Vegan Cafe",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 3120,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/111393759693279042582/photos\"\u003eEdward Aites\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAA1AG430f65Szk7oxVg410t6n7jQyqOVTJQHXxHTeRXlpSQ2Oaj8RDzNbuI54XJwjQgKjJCj2tHw3VZNngHwdg0xYy3MqFiH0VcrSrRrchQT8fgD-wjnCzWLhcps5cgznuEhAr6JcKb8cbYVN3c4-IzDK0GhSSckid9I2Pj2bPm5MT64CMowr1JQ",
               "width" : 4160
            }
         ],
         "rating" : 4.6
      }
   ],
   "debug_log" : {
      "line" : []
   },
   "status" : "OK"
}

now all you have to do is figure out what you want your locationbias parameter to be.

on the other hand, having typed all that out, i look back at your code and realize maybe you wanted to get the place id and then look that up?

anyway, i hope this helps…


#5

Wait, are we using the Places library part of Google Maps API or the Places Web Service?

Also, how do you get back the object?

My intent is to get a list of nearby places matching the search query ‘vegan’, and display details about those places. User should only have to enter their postal code and click the button.

I did not realize that I needed to use extra fields to get more information. Thank you for pointing that out. So if I want photos, name, and opening time, how do I add those fields? I understand the URL, but it’s not like I just punch that in as the endpoint URL, right?

As far as I know, the endpoint URL is one thing, while you have to create parameters to add onto that URL? Hence having a “key” key:value pair…? Or am I misunderstanding?

edit: So, it appears that I can just change the URL I’m calling against. I thought that had to be just the endpoint.

So I could just add a single parameter, that being the user’s inputted postal code, in place of the code I have in my params object now. I haven’t played with this yet, though.

Also, still getting that origin error.


#6

OK, if I were you I would rewrite this part of your code

$.getJSON(GEOCODE_URL, params, callback)

to use $.ajax like in the SO post you linked to.

you should be able to figure out how to change it by reading this: https://api.jquery.com/jquery.ajax/

if you’re still stuck tomorrow afternoon, let me know and i will fork your repo and dig in a little more.


#7

edit: Working on ajax call now. Updated branch. Getting closer!

I am seeing the object when I navigate to that URL. Now, I need to decide which Fields I want, how to get more than one result, and how to access those Fields. I’m sure there’s even more to it than that though. Hah!

It appears that I’m having trouble passing on the user’s location, which I am attempting to grab from my event listener and plug in via that getJSON request.

edit: I’ve gotten it to where there are no errors. However, now I need to figure out how to access the API data.
edit: I think I’ve identified several issues I’m having. The main one is that it looks like I’m not actually geocoding the user’s inputted postal code to a latlng. My user story should go as such:

  • User inputs postal code.
  • User is shown nearby places with the term ‘vegan’ in their data.

So I need to capture that postal code (which I’m doing fine), then convert it to geocode (I don’t think that’s happening), then pass that geocode on to another function that will handle it and get nearby places with the Places API and their details with the Details API, then display them. I think I’ve spent so long on this that I’ve forgotten how to do any of it and sometimes even lose track of what I’m trying to do (I accidentally rewrote the geocoder function earlier thinking it was doing something else.)

More Edits:
I found a video instructing how to use Geocoder. I feel so lost, but came up with this:


function geoCoder(loc, callback){
    console.log('geoCoder called');
    let geocoder = new google.maps.Geocoder();
    window.getCoordinates = function(address, callback){
        var coordinates;
        geocoder.geocode({ address: `${loc}` }, function(results, status){
            coordObj = results[0].geometry.location;
            coordinates = [coordObj.lat,coordObj.lng]
            callback(coordinates);
        })
    }
}

Now, I’m wondering how to get that ltlng out of there. I know it’s easy. I’m just forgetting how… I need to be able to access it with my function(s) for getting the Places and the Details.


#9

None of this is working. :frowning:


#10

blegh. i’m sorry is is so frustrating and that your mentor isn’t being more helpful. i won’t really have time to dig into your repo until thursday or friday, but i am making a note for myself now to do that if someone else doesn’t beat me to it.

keep on trying, we all beat our heads against the wall sometimes.


#11

@SlouchingToast

Are you trying to display nearby locations/POI/branches/stores near a user? I’ve done plenty of these kind of projects.

What I do is have a database (or a list collection/array in JS if there’s not many of them) of all the places . Along with each location, is stored the LAT and LNG coordinates of the place.

When a web visitor lands on your page, you try to guesstimate their location (City, State) via their IP address -or- query the browser and ask for the user’s location (in LAT/LNG).

If you use a web service that gets the user’s location (for example: http://ip-api.com/json) then now you have all the pieces of information you need. (1) The user’s Lat/Lng and (2) all the places Lat/Lng.

Now using a distance formula with a given radius (r, in miles… for example 10 mile radius from user’s location), you can query in your database all the matching places that meets the criteria, i.e. within 10 mile radius from user.

It’s called the Haversine formula for computing distances between (2) Lat/Lng locations.
https://andrew.hedges.name/experiments/haversine/

So now, it’s just a matter of dropping map markers using the places Lat/Lng and placing map icons on your map.

See Google API for how to do this.

PS: As of June 11, 2018 – access to Google API now requires an API Key, and therefore a Credit Card on file!

PPS: You can use an alternative service (like Mapbox.com) where you get 50,000 map views a month for free. Then it’s just $0.50 per 1K map views over 50K.

Here’s mapbox’s version:

They have a differenet API from Google Maps, but similar. You basically set center point Lat/Lng, zoom factor, and other options as a JS object.


#12

@SlouchingToast are you still stuck? I can spend some time digging through the repo tomorrow if you still need help.


#13

@SlouchingToast I swung by your repo and saw this commit msg “all core features operable.” Really hoping that means you figured it out!