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

} 

だから、私は何かを警告しようとしているわけではありませんが、それが私が問題を見つけた方法です。true の場合、myloc is undefined. false の場合はmyloc = Object objectです。そのnavigator.geolocation機能mylocに認識できるものはありますか?

var myloc初期化関数の外で宣言することで、すべてがグレービーだと思いました。スコープの問題?グーグルマップの策略?

4

1 に答える 1

0

ジオロケーティングは非同期プロセスです。

のコールバックgetCurrentPositionが実行された時点で、マーカーは既に作成されています。これは、ブラウザーがユーザー位置を要求している間もスクリプトを実行し続けるためです。

于 2013-02-06T00:02:45.433 に答える