2013-08-28 79 views
0

下面是我正在處理的一些粗略的代碼。所有我想要做的,現在是返回var geoOutput,所以我可以存儲它並在以後使用它。在這個例子中,它應該提醒城市和州。如果我在成功範圍內發出警報,但是在地理定位功能之外返回未定義狀態,則工作正常。如何獲取地理位置以返回jQuery中的變量?

$(function(){ 
    var geoOutput; 
    var geoGet; 
    function getGeoLocation(geoType,displayType){ 
     if(navigator.geolocation){ 
       navigator.geolocation.getCurrentPosition(geoSuccess, geoError); 
      } 
      else { 
       $('.your-location').remove(); 
      } 
     function geoSuccess(position) { 
      console.log(position.coords.latitude+', '+position.coords.longitude); 
      var geoCoder = new google.maps.Geocoder(); 
      var userLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 
      geoCoder.geocode({'latLng':userLocation}, function(results,status){ 
       if (status == google.maps.GeocoderStatus.OK) { 
        if (results) { 
         if(geoType == "zip") { 
          geoOutput = results[2].address_components[0].long_name; 
         } 
         if(geoType == "state") { 
          geoOutput = results[6].address_components[0].long_name; 
         } 
         if(geoType == "city") { 
          geoOutput = results[3].address_components[0].long_name; 
         } 
         if(geoType == "cityState") { 
          geoOutput = results[3].address_components[0].long_name+", "+results[6].address_components[0].long_name; 
         } 
         if(geoType == "coords") { 
          geoOutput = position.coords.latitude+","+position.coords.longitude; 
         } 
         if(geoType == "longitude") { 
          geoOutput = position.coords.longitude; 
         } 
         if(geoType == "latitude") { 
          geoOutput = position.coords.latitude; 
         } 
         if(displayType) 
          $('.your-location').text(geoOutput); 
         return geoOutput; 
        } else { 
         console.log('Google did not return any results.'); 
         $('.your-location').remove(); 
        } 
       } else { 
        console.log("Reverse Geocoding failed due to: " + status); 
        $('.your-location').remove(); 
       } 
      }); 
     } 
     function geoError(err) { 
      if (err.code == 1) { 
       //console.log('The user denied the request for location information.'); 
       $('.your-location').text('State Not Found'); 
      } else if (err.code == 2) { 
       //console.log('Your location information is unavailable.'); 
       $('.your-location').remove(); 
      } else if (err.code == 3) { 
       //console.log('The request to get your location timed out.'); 
       $('.your-location').remove(); 
      } else { 
       //console.log('An unknown error occurred while requesting your location.'); 
       $('.your-location').remove(); 
      } 
     } 
    } 

    alert(getGeoLocation("cityState",false)); 
}); 

回答

相關問題