0
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 %>

} 

所以,我不是想提醒一些东西,但这就是我发现问题的方式。为真时,myloc is undefined. 为假时,为myloc = Object object. navigator.geolocation该功能中是否有可以myloc被识别的东西?

我想通过var myloc在初始化函数之外声明,一切都是肉汁。范围问题?谷歌地图诡计?

4

1 回答 1

0

地理定位是一个异步过程。

getCurrentPosition执行的回调时,标记已经创建,因为浏览器在请求用户位置时会继续执行脚本。

于 2013-02-06T00:02:45.433 回答