Uncaught TypeError: Cannot set property 'posit

2019-01-18 08:31发布

I have this code giving me the strange error message

Uncaught TypeError: Cannot set property 'position' of undefined

This is the inside of a jQuery plugin to show a google map in a popup. I was using the code somewhere else, where it worked fine - the only difference here seems to be that I'm now using it in a Popup window. Am I missing a scope issue or something? All the variables like geocoderParams and latlng are filled like they should. Googling the the error message turned up nothing valuable.

The error message gets fired when the google.maps.Map() is called.

self = $(this)
self.hide()

geocoder = new google.maps.Geocoder
geocoderParams =
  address: self.data('address') || settings.address
  region: settings.region

results = geocoder.geocode geocoderParams, (results, status) ->

if status == google.maps.GeocoderStatus.OK
  latlng = results[0].geometry.location

  mapOptions =
    mapTypeControl: false
    overviewMapControl: false
    zoom: settings.zoomLevel
    center: latlng
    mapTypeId: google.maps.MapTypeId.ROADMAP

  map = new google.maps.Map(self, mapOptions)

self.show()

3条回答
ら.Afraid
2楼-- · 2019-01-18 08:57

I looked up google.maps.Map() and the Google reference says that the first parameter should be a mapDiv:Node which is the container for the map and is typically a div element.

You are passing $(this) which is likely a jQuery object which is not what Google maps is expecting. I don't know the rest of your code, but perhaps you should just be passing this instead of $(this).

查看更多
趁早两清
3楼-- · 2019-01-18 08:59

If you're using jQuery, you need to pass the vanilla HTMLElement (e.g. Node) instead of the jQuery selection (e.g. Array/NodeList) which the $() query returns.

if you add a console command:

console.log(self);

it will return something like:

[ ▶ <div id="map_canvas"></div> ]

to get the value from the jQuery array, replace:

map = new google.maps.Map(self, mapOptions)

with:

map = new google.maps.Map(self[0], mapOptions)
查看更多
Evening l夕情丶
4楼-- · 2019-01-18 09:09

I encountered this error when trying to initiate the map with something like this:

map = new google.maps.Map($('#map-canvas'), mapOptions);

I was able to solve it by selecting the first (and only) item that the selector returns by adding [0] after the selector:

map = new google.maps.Map($('#map-canvas')[0], mapOptions);
查看更多
登录 后发表回答