I have a class MapHandler.
I created an object myMaphandler = new MapHandler and called initialize method.
But @userLocationMarker.getPosition() is returning null 🙁
If I’ll comment alert and call @userLocationMarker.getPosition() from Chrome JS console I getting necessary coordinates.
class window.MapHandler
initialize: (centerLocation) ->
@makeMap(centerLocation)
@defineUserLocation()
alert @userLocationMarker.getPosition()
makeMap: (centerLocation) ->
myOptions =
zoom: 14
center: centerLocation
mapTypeId: google.maps.MapTypeId.ROADMAP
@map = new google.maps.Map(document.getElementById("map_canvas"), myOptions)
placeMarker: (location, icon_path) ->
if icon_path
markerImage = new google.maps.MarkerImage(icon_path, null, null, null, new google.maps.Size(25, 25))
else
markerImage = null
marker = new google.maps.Marker(
position: location
map: @map
icon: markerImage)
defineUserLocation: () ->
@userLocationMarker = @placeMarker(null, null)
handleMap = (position) =>
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
infowindow = new google.maps.InfoWindow(
map: @map
position: pos
content: 'Если это не ваше местоположение - передвиньте маркер'
)
@map.setCenter(pos)
@userLocationMarker.setPosition(pos)
if navigator.geolocation
@userPosition = navigator.geolocation.getCurrentPositon(
handleMap
)
Why this occurs and what I should do for avoiding this situation?
You initialize
@userLocationMarkerwith anullposition:And then you set the “real” positon in
handleMap:which is used as a callback for
getCurrentPosition:The problem is that
getCurrentPositionis asynchronous so youralertis getting called beforehandleMaphas been called bygetCurrentPosition. Anything that depends on whatgetCurrentPositiondoes has to be in thehandleMapcallback or they need to be prepared to deal with data that hasn’t arrived yet.There’s also a typo in your example code, you spelled
getCurrentPositionwrong in yourif navigator.geolocationblock.By the time you try checking the position from the JavaScript console,
getCurrentPositionhas calledhandleMapand@userLocationMarkerwill have had its position properly initialized.