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);

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);

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.
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
    });
    },
    });
    });

    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)

    Have you ideas about that?

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*