Search code examples
angularjsgoogle-maps-api-3ng-map

Using ngMap in gulp project - build failing - getting 'google' is not defined


I've set up an angular project using Yeoman, and embedding a google map in a page using ngmap, using a given address to centre it. I'm adding a marker to the map using the google geocode service to get the latitude/longitude for the address, once the map has been initialised.

var vm = this;
vm.address = '1600 Pennsylvania Ave NW, Washington, DC 20500, United States';
NgMap.getMap().then(function() {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    address: vm.address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
    vm.markerPosition = '[' + results[0].geometry.location.lat() + ', ' + results[0].geometry.location.lng() + ']';
    } else {
    console.log("Unable to retrive details for address: " + address);
    }
  });
});

It's working fine, I've a plunkr running here - https://plnkr.co/Ex91VGqdFmL9FP78uzU0?p=preview - but when I run the build using gulp build I get this error, and the same when I run the unit tests:

'google' is not defined

What do I need to inject, or mock, so that the call to google.maps.Geocoder doesn't fail?

As requested, this is the index.html from the build

<!doctype html>
<html ng-app="myApp">
  <head>
    <base href="/">
    <meta charset="utf-8">
    <title translate>title</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="icon" type="image/png" href="images/icon.png">
    <link rel="stylesheet" href="styles/vendor-d41d8cd98f.css">
    <link rel="stylesheet" href="styles/app-2dd2bcbbbd.css">
  <script src="https://maps.google.com/maps/api/js"></script>
  </head>
  <body>
        <main ui-view></main>
  </body>
  <script src="scripts/vendor-83b6c91f4a.js"></script>
   <script src="scripts/app-41321c4301.js"></script>
</html>

Solution

  • Read through some of the examples of ngMap and it turns out the marker directive can take an address as a parameter, which it converts to lat/lon values automatically. So the solution is to remove all the google.maps.Geocoder and just this in the html.

    <marker position="{{myMapCtrl.address}}" title="Marker"></marker>
    

    and to learn to read all the documentation before attempting to use a library