如何从网络网址获取地理位置

How to get Geo location from the WebURL

本文关键字:获取 地理位置 网络      更新时间:2023-09-26
  • 我创建了一个 ASP.NET 网站并将其托管在服务器上。
  • 假设我的 Web 访问 URL 是 "www.xyz.com"
  • 现在,我想要访问我的网站并将其显示在Google地图上的Geo Location。或者我可以从访问此 Web URL 的位置获取latitudelongitude

那么,这可能吗?

使用 HTML 地理位置。HTML 地理位置 API 用于定位用户的位置。你可以得到纬度和经度!这是我的代码:

if (navigator.geolocation) {
    // support geolocation
    var success = function(position){
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        console.log('here latitude :'+latitude+' && longitude :'+longitude);
    }
    var errors = function(){
        console.log('not working');
    }
    navigator.geolocation.getCurrentPosition(success, errors);
} else {
    alert('upgrade your browser !');
}

我的输出是:这里纬度:37.5030042&&经度:127.0507571

编辑

您希望查看访问您网站的所有用户地理位置。我认为有两种方式。使用谷歌分析API与谷歌地图或使用ajax(5秒更新新的地理位置数据到html和你的数据库(mysql,dynamo,redis等)。

 if (navigator.geolocation) {
         // support geolocation
         var success = function(position){
             latitude = position.coords.latitude;
             longitude = position.coords.longitude;
             console.log('here latitude :'+latitude+' && longitude :'+longitude);
             setInterval(function(e){
                 $.ajax({
                   type: "get",
                   dataType: 'json',
                   url: 'here request url',
                   cache: false,
                   data: { // request user geo data
                       latitude : latitude,
                       longitude : longitude
                   }
                 }).done(function(xhr) {
                     if(xhr.status){
                         // response users geo data and update your html DOM
                         $('#maps').html(xhr.geo.datas)
                     }else{
                         alert(xhr.msg);
                     }
                 })
             },5000); // default 5 second
         }
         var errors = function(){
             console.log('not working');
         }
         navigator.geolocation.getCurrentPosition(success, errors);
     } else {
         alert('upgrade your browser !');
     }

这是HTML代码

<asp:GridView ID="gridView1" runat="server" AutoGenerateColumns = "false">
    <Columns>
        <asp:BoundField DataField="IPAddress" HeaderText="IP Address" />
        <asp:BoundField DataField="CountryName" HeaderText="Country" />    
        <asp:BoundField DataField="Latitude" HeaderText="Latitude" />
        <asp:BoundField DataField="Longitude" HeaderText="Latitude" />
    </Columns>
</asp:GridView>

这是 C# 代码:

protected void Page_Load(object sender, EventArgs e)
{
    string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (string.IsNullOrEmpty(ipAddress))
    {
        ipAddress = Request.ServerVariables["REMOTE_ADDR"];
    }
    string APIKey = "<Your API Key>";
    string url = string.Format("http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=json", APIKey, ipAddress);
    using (WebClient client = new WebClient())
    {
        string json = client.DownloadString(url);
        Location location = new JavaScriptSerializer().Deserialize<Location>(json);
        List<Location> locations = new List<Location>();
        locations.Add(location);
        gridView1.DataSource = locations;
        gridView1.DataBind();
    }
}

public class Location
{
    public string IPAddress { get; set; }
    public string CountryName { get; set; }      
    public string Latitude { get; set; }
    public string Longitude { get; set; }       
}

尝试这样获取用户的位置:除非您设置超时和错误,否则您获取当前位置的请求可能永远不会返回。

window.onload = function() {
  var startPos;
  var geoOptions = {
  timeout: 10 * 1000
}
var geoSuccess = function(position) {
  startPos = position;
  document.getElementById('startLat').innerHTML = startPos.coords.latitude;
  document.getElementById('startLon').innerHTML = startPos.coords.longitude;
};
var geoError = function(error) {
  console.log('Error occurred. Error code: ' + error.code);
  // error.code can be:
  //   0: unknown error
  //   1: permission denied
  //   2: position unavailable (error response from location provider)
  //   3: timed out
 };
   navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
 };