隐藏的“纬度”和“lng”字段没有被删除,所以我的脚本仍在从不正确的地理位置中搜索纬度和液化天然气结果

The hidden 'lat' and 'lng' fields were not removed and so my script was still searching for the lat and lng results from the incorrect geolocation

本文关键字:纬度 地理位置 不正确 天然气 结果 搜索 字段 lng 删除 我的 隐藏      更新时间:2023-09-26

我有一个页面,用户可以在其中输入他们的地址到"邮政编码"字段中。我还有一个"检测位置"按钮,可以对用户地址进行地理定位。当他们点击此按钮时,他们的城市名称和邮政编码将回显到"邮政编码"字段中,纬度和经度将传递到两个动态创建的隐藏输入字段中。我在页面上也有地点 API。

回显地址和邮政编码并创建隐藏字段的代码如下所示:

if (results[1]) {
    split1 = results[1].formatted_address.split(', ');
    // echo the geolocation address into the 'zipcode' input field
    document.getElementById('zipcode').value = split1[1] + ', ' + split1[2]; // city name and postcode
    // if hidden lat and lng fields are present from Places API, remove them
    $(".storelocator_body form").find("input.geomtery").remove();
    // produce new hidden fields with the new lat and lng values
    $(".storelocator_body form").append("<input type='hidden' class='geomtery' name='lat' value='" + lat + "'>");
    $(".storelocator_body form").append("<input type='hidden' class='geomtery' name='lng' value='" + lng + "'>");
} else {
    alert("No results found");
}

我遇到的问题是,有时地理位置会给出虚假的结果,特别是如果我在没有无线网卡的情况下从桌面搜索。当我手动将"邮政编码"输入字段更改为正确的地址时,隐藏的"lat"和"lng"字段没有被删除,因此我的脚本仍在从不正确的地理位置中搜索纬度和液化天然气结果。

我想出的解决方案如下:

if(document.getElementsByClassName("geomtery")){
    $("#zipcode").on("input",function(e){
        $(".storelocator_body form").find("input.geomtery").remove();
    });
}

我的想法是,如果用户开始在"邮政编码"输入字段中键入甚至粘贴新地址,并且已经存在隐藏的"纬度"和"LNG"字段,那么这些字段将被删除。

你觉得怎么样?我用最好的方式做到了吗?我是编码新手,希望得到一些反馈。非常感谢。

为什么要让自己很难受?与其每次都进行 DOM 插入,您可以简单地检测字段是否存在(或者更好的是,直接将它们包含在 HTML 中),并更改它们的值。

 // here your Places code, field as optional parameter (to retrieve from zipcode afterwards)  
function placesAPIcall(field) { [...] return { lat: 'value', long: 'value'}}
// on page load
function initPlaces() {
   var result = placesAPIcall(), lat = result.lat, lng = result.lng;
   if (!$('.geomtery[name=lat]').length)
      $('.storelocator_body form').append('<input type="hidden" class="geomtery" name="lat" value="' + lat + '">');
   if (!$('.geomtery[name=lng]').length)
      $('.storelocator_body form').append('<input type="hidden" class="geomtery" name="lng" value="' + lng + '">');
}
// everytime #zipcode loses focus, value updates
function updateLatLong() { 
   var result = placesAPIcall($('#zipcode')), lat = result.lat, lng = result.lng;
   $('.geomtery[name=lat]').val(lat); // set the value
   $('.geomtery[name=lng]').val(lng); // set the value
});
$('#zipcode').on({'change': updateLatLong, 'load': initPlaces});

一些提示:

  • 在单引号(")和双引号(')之间进行选择并保持一致。
    就我个人而言,我总是将"用于HTML,'用于JS。
  • 据我所知,jQuery中没有input事件,请使用changekeyup或表单submit代替。
  • 您在函数中发送了e(事件)作为参数:您应该只包含所需的参数(在本例中没有),否则可能会使阅读您代码的其他人感到困惑。
  • 一致的编码风格:如果你选择使用jQuery,那么使用像document.getElementsByClassName这样的原生JS函数是没有意义的,因为它在IE8和jQuery的更简单的类选择器中不起作用,相比之下,$('.class')可以。
  • 几何geomtery错别字?