如何删除未定义的对象错误并根据位置重定向用户

How to remove undefined object error and redirect user based on location?

本文关键字:错误 位置 用户 重定向 对象 何删除 删除 未定义      更新时间:2023-09-26

我正在开发一种地理定位功能,该功能可将用户重定向到各自城市的页面。我使用Google Maps API和HTML5 Geolocation来尝试实现这一点。在运行以下脚本时,地址在控制台中显示为一个对象。但是,当我尝试在后续行进行比较时,我收到一个错误,说 Undefined 不是对象(评估"地址.结果"。如何使代码工作?

<script type="text/javascript">
  var GOOGLE_API_KEY = "mykey";
  var lat, lng;
  var geocoder;
  var geoCodingUrl;
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  }
  function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    var geoCodingUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&key=" + GOOGLE_API_KEY;
    console.log(geoCodingUrl); 
    var address = $.get(geoCodingUrl);
console.log(address);
  if (address.results[0].formatted_address[4] == "Mumbai, Maharashtra, India") {
    window.location = "url";
  } 
  if(address.results.long_name == "Bangalore, India"){
    window.location = "url";
  } 
  if(address.results.long_name == "Jaipur, India") {
    window.location = "url";
  }
  }
function errorFunction() {
   alert ("Geocoder failed");
}
</script>

试试这个

$.get({url:geoCodingUrl,success:function(response){
    var address=response.results;
    if (address[0].formatted_address[4] == "Mumbai, Maharashtra, India") {
    window.location = "url";
    } 
   if(address[0].long_name == "Bangalore, India"){
     window.location = "url";
   } 
   if(address[0].long_name == "Jaipur, India") {
     window.location = "url";
   }
}
})