[英]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.