var myloc;
function initialize() {
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var mylocOptions = {
draggable: true,
animation: google.maps.Animation.DROP,
title: "You are here..."
};
myloc = new google.maps.Marker(mylocOptions);
<% if !signed_in? || !current_user.loc %>
if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
$.ajax({
data: { me: me.toString() },
type: 'POST',
url: '/set-location'
})
}, function(error) {
var address = prompt('Where are you looking?');
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var me = results[0].geometry.location
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
} else {
alert("Geocode was not successful for the following reason: " + status);
};
});
});
<% else %>
var me = new google.maps.LatLng(<%= current_user.loc %>);
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
<% end %>
}
So, I’m not trying to alert stuff, but that’s how I found the problem. When true, myloc is undefined. When false, it’s myloc = Object object. Is there something in that navigator.geolocation function that allows myloc to be recognized?
I thought by declaring var myloc outside of the initialize function, everything was gravy. Scope issue? Google maps trickery?
Geolocating is an asynchronous process.
At the time when the callback of
getCurrentPositionis executed, the marker has already been created, because the browser will continue executing the script while he requests the user-position.