[英]How to get Latitude and Longitude of any City using Google API and a form?
[英]User selects city from options in form and pass longitude and latitude to api
我想将经度和纬度传递给地理名称 api。 目前我有两个 select 字段,用户在其中选择城市经度和相应的城市纬度:
<select id="selectLat">
<option value="30.26057">Chicago Latitude</option>
<option value="51.5074">London Latitude</option>
<option value="50.0755">Prague Latitude</option>
</select>
<select id="selectLng">
<option value="-97.771889">Chicago Longitude</option>
<option value="0.1278">London Longitude</option>
<option value="14.4378">Prague Longitude</option>
</select>
提交选择后,这些值将传递给地理名称 api 并且我可以使用返回的 JSON 数据。 但我真正想要发生的是用户只选择城市名称。 经度和纬度值将被组合,然后以某种方式解析/分离并传递给 api。 有没有办法做到这一点?
我正在使用 jQuery 和 php 来处理 api 请求顺便说一句。
$.ajax({
url: "test.php",
type: 'POST',
dataType: 'json',
data: {
lat: $('#selectLat').val(),
lng: $('#selectLng').val()
},
您可以使用data-
属性,例如:
<option data-longitude="..." data-latitude="...">city</option>
然后
$.ajax({
url: "test.php",
type: 'POST',
dataType: 'json',
data: {
lat: $('#citySelect option:selected').data("latitude"),
lng: $('#citySelect option:selected').data("longitude"),
},
保持数组,以便每个城市都有其经度和纬度,在选择城市时,您将从阵列中删除阵列中的信息。
HTML:
<select id="select_city">
<option value="chicago">Chicago Latitude</option>
<option value="london">London Latitude</option>
<option value="prague">Prague Latitude</option>
</select>
JS:
const c = "{'prague' : {'latitude': 50.0755, 'longitude': 14.4378}, 'london': {'latitude': 50.0755, 'longitude':14.4378}}";
.
.
.
lat = c[${'#select_city').val()].latitude;
lng = c[${'#select_city').val()].longitude;
$.ajax({
url: "test.php",
type: 'POST',
dataType: 'json',
data: {
lat: lat,
lng: lng
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.