【问题标题】:How to get city name using geolocation and redirect to an URL for that city?如何使用地理位置获取城市名称并重定向到该城市的 URL?
【发布时间】:2018-02-02 19:14:08
【问题描述】:

例如,如果用户访问http://example.com,我根据地理位置将“纽约”作为城市,则将用户重定向到http://example.com/NY

如果是“洛杉矶”重定向到http://example.com/LA,如果是任何其他城市,用户将被定向到第三个 URL。

我该怎么做?

这是我当前的尝试/代码:

<!DOCTYPE html>
<html>
<head>
    <title>GEOIP DB - jQuery example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
    <div>Country: <span id="country"></span>
    <div>State: <span id="state"></span>
    <div>City: <span id="city"></span>
    <div>Latitude: <span id="latitude"></span>
    <div>Longitude: <span id="longitude"></span>
    <div>IP: <span id="ip"></span>
    <script>
        $.ajax({
            url: "https://geoip-db.com/jsonp",
            jsonpCallback: "callback",
            dataType: "jsonp",
            success: function( location ) {
                $('#country').html(location.country_name);
                $('#state').html(location.state);
                $('#city').html(location.city);
                $('#latitude').html(location.latitude);
                $('#longitude').html(location.longitude);
                $('#ip').html(location.IPv4);  
                $routes = {"Los Angeles": "http://google.com/LA", "New York": "http://google.com/NY"}
if ( routes[location.city] ) { window.location.href = routes[location.city] }
            }

        }); 

    </script>
</body>
</html>

【问题讨论】:

    标签: javascript jquery html geolocation


    【解决方案1】:

    根据我在您的代码中看到的,您必须将所需的城市添加到路线对象中,如下所示:

    {
     "Los Angeles": "http://google.com/LA", 
     "New York": "http://google.com/NY", 
     "Other City": "http://google.com/othercity"
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多