Google Maps API: Cannot set property ‘position’ of undefined

Cannot set property 'position' of undefined

If the Google Maps API v3 is returning this error here's how to fix it.

Problem

I've used jQuery to get the map container but then it starts returning an error.

map = new google.maps.Map($('#my-map'), mapOptions);
Code language: JavaScript (javascript)

Solution

Try using the following code to get the map container:

var mapElem = $("#container").find("#my-map")[0]; map = new google.maps.Map(mapElem, mapOptions);
Code language: JavaScript (javascript)

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

3 comments
  • Hi Rick,
    Thanks for nice article.

    I’ve tried your code to fix my error. My codes below:

    define([ 'require', 'backbone', 'text!../templates/list.html', ], function(Require, Backbone, Template){ return Backbone.View.extend({ tagName: 'div', template: _.template(Template), initialize: function(){ this.render(); }, render: function(){ var self = this; this.$el.html(this.template()); self.initMap(); }, initMap: function(){ debugger; var target = { lat: 1.098706, lng: 104.026971 }; var mapOption = {zoom: 12, center: target }; var mapElem = $(".container").find("#map-canvas"); var map = new google.maps.Map(mapElem, mapOption); var marker = new google.maps.Marker({ position: target, map: map }); }, }); });
    Code language: JavaScript (javascript)

    If I use $(“.container”).find(“#map-canvas”)[0]; the result is undefined. Caused it I remove the index [0] from my code. But I am still getting error:

    Uncaught TypeError: Cannot set property 'position' of undefined at new _.hv (common.js:141) at Object.Wy.f (map.js:56) at Array. (js?key=xxxxxxxxxxxxxx:90)
    Code language: PHP (php)

    Have you ideas about that?

Leave a Reply

Add <code> Some Code </code> if you need to.

*
*