2013-10-22 56 views
0


我已经通过我的相关问题,每一个可能的问题,并试图解决许多,似乎没有任何帮助。我使用Google的Map API,并且地图不是以正确的经纬度对为中心。它指向(0,0),这是南太平洋中部的一些地方。在对我的Lat Long对进行地理定位时,它会给出正确的地址。
这里是我的代码:谷歌地图API不居中正确的位置

$(document).ready(function(){ 
    var loc = {lat:0,long:0}; 
    if (navigator.geolocation){ 
    navigator.geolocation.getCurrentPosition(showPosition); 
    }else{ 
    alert("Geolocation is not supported by this browser."); 
    } 
    console.log(loc); 
    function showPosition(position){ 
    loc.lat=position.coords.latitude; 
    loc.long=position.coords.longitude; 
    var geocoder = new google.maps.Geocoder(); 
    var latLng = new google.maps.LatLng(loc.lat, loc.long); 
    console.log(latLng); 
    if (geocoder) { 
     geocoder.geocode({ 'latLng': latLng}, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      console.log(results[0].formatted_address); 
      alert('Address:'+results[0].formatted_address); 
     }else { 
      console.log("Geocoding failed: " + status); 
     } 
     }); //geocoder.geocode() 
    } 
    } 
    var latLong = new google.maps.LatLng(loc.lat, loc.long); 
    var mapOptions = { 
    center: latLong, 
    useCurrentLocation : true, 
    zoom: 14, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    var mapMsg = new google.maps.Map(document.getElementById("local_map"), mapOptions); 
    google.maps.event.addDomListener(window, 'load'); 
    var markerOptions = new google.maps.Marker({ 
    clickable: true, 
    flat: true, 
    map: mapMsg, 
    position: latLong, 
    title: "You are here", 
    visible:true, 
    icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', 
    }); 
}); 


这里是Firefox的控制台显示正确的位置地址和LAT长的屏幕截图。

Firefox Console

控制台中的前两行是坐标,第三行是地理编码的位置。
请告诉我我错了。我知道这将是一个愚蠢的错误,但我是新手。

问候

回答

1

你永远不会获得来自地理编码结果的位置,或者设置的标志 - 和执行的顺序是颠倒(但不会失败)

而是执行此操作:

... 
if (status == google.maps.GeocoderStatus.OK) { 
    var markerOptions = new google.maps.Marker({ 
    clickable: true, 
    flat: true, 
    map: mapMsg, 
    position: results[0].geometry.location, 
    title: "You are here", 
    visible:true, 
    icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', 
    }); 
    var marker = new google.maps.Marker(markerOptions); 
    mapMsg.setCenter(results[0].geometry.location); 
    } else { 
    console.log("Geocoding failed: " + status); 
    } 
    ... 

这里你的代码的莫名其妙清洗/工作版本http://jsfiddle.net/zqeCX/ 但你真的应该考虑使用的谷歌地图的例子作为出发点之一,得到了执行流程的权利。

+0

嗨,谢谢你的帮助。该商标正在工作! 可以请你解释一下这个原因吗? –

1

这是因为navigator.geolocation.getCurrentPosition是异步。 因此,当你做var latLong = new google.maps.LatLng(loc.lat, loc.long);loc.lat仍然是“0”,因为是loc.long

所以你需要包括做线在你的函数showPosition