Call Google API with no HTML gives error "google is not defined"

709 views Asked by At

This issue is clearly a duplicate, but I cannot find a solution to the problem that does not contain HTML code. I am coding node js to use for a bot so everything happens inside the javascript. I need to use StreetViewService but not sure how to call Google API or if I need a module.

var request = require('request');

function initialize() {
  var latLong = {lat: -33.867386, lng: 151.195767};
  var streetviewService = new google.maps.StreetViewLocationRequest();
  streetviewService.getPanorama(
    {location: latLong,
    preference: NEAREST,
    radius: 200,
    source: OUTDOOR},
    function(streetViewPanoramaData, status) {
      if (status === google.maps.StreetViewStatus.OK) {
        newLatLng = streetViewPanoramaData.location.latLng;
      }
    });
  }

  nearestStreetViewUrl = 'https://maps.googleapis.com/maps/api/js?key='+ process.env.GoogleApiKey + '&callback=' +initialize();
  request(nearestStreetViewUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
     console.log(body);
     // do something
   }
 });

This code gives error "google is not defined". I believe I am not calling the API correctly, or missing something.

1

There are 1 answers

3
Theodorus On

In the following line you are actually executing the initialize() method and pasting the result to the end of the string:

nearestStreetViewUrl = 'https://maps.googleapis.com/maps/api/js?key='+ process.env.GoogleApiKey + '&callback=' +initialize();

You should set the method name as the value of the callback query parameter, like so:

nearestStreetViewUrl = 'https://maps.googleapis.com/maps/api/js?key='+ process.env.GoogleApiKey + '&callback=initialize';

This should get you at least one step further.