2011年4月28日 星期四

GeoLocation sample code

var initialLocation = new Object();
    initialLocation.type = "CHT_Xinyi";
    initialLocation.x = "121.52435034130934";
    initialLocation.y = "25.03645913419541";
    initialLocation.h = "0";
    initialLocation.cityName ="";
    initialLocation.countryCode="";
    initialLocation.countryName = "TAIWAN";
   
function getUserGeoLocation(){
   
    var browserSupportFlag =  new Boolean(false);
    // Try W3C geolocation
    if(navigator.geolocation) {
        browserSupportFlag = true;
        //successCallback
        navigator.geolocation.getCurrentPosition(function(position) {
          
            initialLocation.type = "Location found using W3C standard";
            initialLocation.x = position.coords.longitude;
            initialLocation.y = position.coords.latitude;
            initialLocation.h = position.coords.altitude;;
            $("#type").html(initialLocation.type);
            $("#x").html(initialLocation.x);
            $("#y").html(initialLocation.y);
            $("#h").html(initialLocation.h);
            $("#cityName").html(initialLocation.cityName);
            $("#countryCode").html(initialLocation.countryCode);
                      
        //errorCallback
        }, function() {
            alert("navigator.geolocation exist...getCurrentPosition failed");          
        });
    // Try IP location IPInfoDB
    } else if (browserSupportFlag==false) {
   
        var service_url = "http://***********/geolocation/geolocation.aspx";
        $.ajax({
            url: service_url,
            type: 'GET',
            dataType: 'json',
           // async:false,
            error: function (xhr, textStatus) {
                alert(xhr.statusText);
            },
            success: function (data) {
                if (data == null) {
                    alert('NO RESULT');
                } else {
                    initialLocation.type = "Location found using IPInfoDB API";             
                    initialLocation.x = data.longitude
                    initialLocation.y = data.latitude;
                    initialLocation.h = "";
                    initialLocation.cityName = data.cityName;
                    initialLocation.countryCode = data.countryCode;
                    $("#type").html(initialLocation.type);
                    $("#x").html(initialLocation.x);
                    $("#y").html(initialLocation.y);
                    $("#h").html(initialLocation.h);
                    $("#cityName").html(initialLocation.cityName);
                    $("#countryCode").html(initialLocation.countryCode);
                }
            }
        });
    }
}

沒有留言: