Lewis Menelaws
Lewis Menelaws

Reputation: 1186

Uncaught TypeError: Cannot read property 'apply' of undefined Google Maps

I am using Google Maps to make markers on a map and I am trying to convert addresses to geocodes using the following code:

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initialize" async defer></script>

<script type="text/javascript">
var map;

 function initialize() {
   var chamberLocation = {lat: 43, lng: -82};
   var geocoder = new google.maps.Geocoder();
   map = new google.maps.Map(document.getElementById('map'), {
     center: {lat: 42.9745, lng: -82.4066},
     zoom: 14,
     styles: [{"featureType":"road","elementType":"geometry","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"hue":149},{"saturation":-78},{"lightness":0}]},{"featureType":"road.highway","stylers":[{"hue":-31},{"saturation":-40},{"lightness":2.8}]},{"featureType":"poi","elementType":"label","stylers":[{"visibility":"off"}]},{"featureType":"landscape","stylers":[{"hue":163},{"saturation":-26},{"lightness":-1.1}]},{"featureType":"transit","stylers":[{"visibility":"off"}]},{"featureType":"water","stylers":[{"hue":3},{"saturation":-24.24},{"lightness":-38.57}]}],
     zoomControl: false,
     scaleControl: false,
     mapTypeControl: false,
     disableDefaultUI: false,
     streetViewControl: false,
     rotateControl: false,
     scrollwheel: false,
     draggable: false
   });
   codeAddress(geocoder, map);

   }

   function codeAddress(geocoder, map) {
       var address = 'place';
       geocoder.geocode({ 'address' : address }), function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
               var marker = new google.maps.Marker({
                   map: map,
                   position: results[0].geometry.location
               });
           } else {
               console.log('This didnt work' + status);
           }
       };
   }


</script>

Whenever I do this I get an error saying Uncaught TypeError: Cannot read property 'apply' of undefined

What is causing this error? I am unsure as to how to fix this. Do I have to import another google maps api?

Upvotes: 4

Views: 21869

Answers (2)

khan Farman
khan Farman

Reputation: 366

Today i have also faced the same error while using distance matrix library, what we need to do is simply use the callback function mentioned here https://developers.google.com/maps/documentation/javascript/distancematrix

According to this doc https://developers.google.com/maps/documentation/javascript/examples/distance-matrix#maps_distance_matrix-typescript i was using promises thats when i encounterd the above error

var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = new google.maps.LatLng(50.087692, 14.421150);

var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
  {
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: 'DRIVING',
    transitOptions: TransitOptions,
    drivingOptions: DrivingOptions,
    unitSystem: UnitSystem,
    avoidHighways: Boolean,
    avoidTolls: Boolean,
  }, callback);

function callback(response, status) {
  // See Parsing the Results for
  // the basics of a callback function.
  console.log(status);
  console.log(response);
}

Upvotes: 0

Jonathan Portorreal
Jonathan Portorreal

Reputation: 2826

The error is a typo. I put the code below and commented //change in places where the typo was at. geocoder.geocode({}, callback) is a function that takes an object and a callback, but you have geocoder.geocode({ 'address' : address }), the typo is the ) it should be geocoder.geocode({ 'address' : address }, function(results, status) { ...

<div id="map" style="width: 320px; height: 480px;"></div>

  <script type="text/javascript">
    var map;

    function initialize() {
      // your code 
      // etc ... 
      codeAddress(geocoder, map);
    }

    function codeAddress(geocoder, map) {
      var address = 'place';
      geocoder.geocode({
          'address': address
        }, // change
        function(results, status) {
          if (status == 'OK') { // change

            var marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location
            });

            // some debug output
            console.log("status is: " + status)
            console.log("results is: " + JSON.stringify(results[0].geometry.location))
          } else {
            console.log('This didnt work' + status);
          }
        });
    };
  </script>

  <script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initialize"></script>

Upvotes: 6

Related Questions