martincarlin87
martincarlin87

Reputation: 11062

Google Maps v3 - Uncaught TypeError: Cannot read property 'Marker' of undefined

I have my map div container always on the page:

<div id="map_canvas"></div>

at first I was trying to append this to the DOM in the ajax callback aswell but was having troubles so decided to make it static for now.

I am trying to initialise the map from a jquery ajax callback

...
complete: function(data) {
    // build the map
    $.getScript("http://maps.google.com/maps/api/js?v=3&libraries=geometry&sensor=false&region=uk&async=2&callback=MapApiLoaded", function () {});     
    running = false;

    if(running) return false;
    running = true;
    setMarkers();
    flightPath.setMap(null); // Remove polyline
    flightPathProgress.setMap(null); // Remove polyline

    setTimeout(function() {
        flightPath.setMap(map);
        flightPathProgress.setMap(map);
        flightPathProgress.setOptions({
            strokeOpacity: 0
    });

    var progress = 0;
    var intvl = setInterval(function(){
        progress += 0.01;
        if(progress > 1) { 
            clearInterval(intvl);
            running = false;
         } else {

         }

         // Calc progress
         var progressLatLng = google.maps.geometry.spherical.interpolate(userlatlng, serverlatlng, progress);
         // Update polyline
         flightPathProgress.setOptions({
             strokeOpacity: progress,
             path: [userlatlng, progressLatLng]
         });
     }, 50);
     }, 1000);
 }

I also have the following outside of the document ready function

var map;
var serverlatlng;
var userlatlng;
var servermarker;
var usermarker;
var flightPath;
var flightPathProgress;
var running;

function MapApiLoaded() {
    serverlatlng = new google.maps.LatLng(34.0625, -118.123);
    userlatlng = new google.maps.LatLng(54.167, -4.48211);
    var centerlatlng = new google.maps.LatLng(44.0835, -61.241055);

    // Create the map
    var myOptions = {
        center: centerlatlng,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        panControl: false,
        zoomControl: false,
        streetViewControl: false,
        mapTypeControl: false
     };

     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

     // Centre map on user and server locations
     var bounds = new google.maps.LatLngBounds();
     bounds.extend(serverlatlng);
     bounds.extend(userlatlng);
     map.fitBounds(bounds);

     // The grey outline path
     flightPath = new google.maps.Polyline({
         path: [userlatlng,serverlatlng],
         strokeColor: "#666",
         strokeOpacity: 0.5,
         strokeWeight: 4,
         geodesic: true,
         zIndex: 1
      });

      // The red progress path
      flightPathProgress = new google.maps.Polyline({
          path: [userlatlng,userlatlng],
          strokeColor: "#ff0000",
          strokeOpacity: 0,
          strokeWeight: 4,
          geodesic: true,
          zIndex: 2
      });
}

function setMarkers() {
    if(servermarker != undefined) servermarker.setMap(null); // Remove marker if exists
    servermarker = new google.maps.Marker({
    position: serverlatlng, 
    map: map, 
    title:"Server",
    animation: google.maps.Animation.DROP,
    icon: 'images/marker.png'
});  

    if(usermarker != undefined) usermarker.setMap(null); // Remove marker if exists
    usermarker = new google.maps.Marker({
        position: userlatlng, 
        map: map, 
        title:"User",
        animation: google.maps.Animation.DROP,
        icon: 'images/marker.png'
    }); 
}

The error message I am getting is Uncaught TypeError: Cannot read property 'Marker' of undefined.

The full expanded message is

Uncaught TypeError: Cannot read property 'Marker' of undefined     
www.domain.co.uk/:345
setMarkers www.domain.co.uk/:345
$.ajax.complete www.domain.co.uk/:242
fire jquery.js:3064
self.fireWith jquery.js:3176
done jquery.js:8259

callback`

Upvotes: 0

Views: 30806

Answers (5)

Sidius
Sidius

Reputation: 414

if you do not have a business account, it could also give you this error which comes from this response of the server:

{
 "error_message" : "You have exceeded your rate-limit for this API.",
 "results" : [],
 "status" : "OVER_QUERY_LIMIT"
}

Which means that either you load the api too many times a day/too concentrated or that you try to load many addresses. Check the server response and see if you get it.

This particular response will also cause this error.

Uncaught TypeError: Cannot read property 'geometry' of undefined

Here you can find some tips that might help. https://developers.google.com/maps/documentation/business/articles/usage_limits

Upvotes: 1

EJ207
EJ207

Reputation: 49

I solved this because I was missing geometry from the end of this url

  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?    v=3.exp&sensor=false&libraries=places,drawing,geometry"></script>

Upvotes: 5

Amber Haq Dixon
Amber Haq Dixon

Reputation: 614

I think you need to load the JS google maps API using a "script" tag, NOT using $.getScript.

According to the jQuery API docs (http://api.jquery.com/jQuery.getScript/), getScript loads a JavaScript file from the server using a GET HTTP request, then executes it.

This is probably not the right way of loading the Gmaps JS API. Note that the documentation for the GMaps API says, "The URL contained in the script tag is the location of a JavaScript file that loads all of the symbols and definitions you need for using the Google Maps API. This script tag is required. ... To [asynchronously load the JS API], you can inject your own tag in response to a window.onload event or a function call, but you need to additionally instruct the Maps JavaScript API bootstrap to delay execution of your application code until the Maps JavaScript API code is fully loaded. You may do so using the callback parameter, which takes as an argument the function to execute upon completing loading the API."

You can see the gmaps API docs here: https://developers.google.com/maps/documentation/javascript/tutorial

In my case, I did the following. Note that the callback parameter is required for this to work:

function initializeGmaps() {}
$(document).ready(function() {
  $('head').append('<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&callback=initializeGmaps"><\/script>'); 
});

Upvotes: 0

e4c5
e4c5

Reputation: 53774

Apparently this is a bug in the new Google Maps update. It only seems to effect those users who have the new version of maps. For them, the marker will not show up even on the google api code sample: https://developers.google.com/maps/documentation/javascript/examples/marker-simple

The developer console will have the Uncaught TypeError: Type error

if you logout of google and visit the same page, you are most likely to see the marker

Upvotes: 5

geocodezip
geocodezip

Reputation: 161404

You are trying to use the Google Maps API constructor for a google.maps.Marker before the API is loaded.

Update: the setMarkers function is running before the API is loaded.

Upvotes: 5

Related Questions