我仍然嘗試通過 data.gouv API 從地址中提取 Long 和 Lat。我有那個代碼:
function extractLatLngFromAdd($address) {
$address = "paris";
$geodata = json_decode ('https://api-adresse.data.gouv.fr/search/?q='. $address );
// extract latitude and longitude
$result['latitude'] = $geodata->features[0]->geometry->coordinates[1];
$result['longitude'] = $geodata->features[0]->geometry->coordinates[0];
return $result;
}
print_r(extractLatLngFromAdd($address));
然后,通過這個函式,我希望提取下面的陣列:
$lab = array(
"repartition" => array(
array(
"latLng" => array( extractLatLngFromAdd('Paris') ),
"name" => "Paris",
"code" => "FR-75"
),
array(
"latLng" => array( extractLatLngFromAdd('grenoble') ),
"name" => "Grenoble",
"code" => "FR-38"
)
)
);
echo json_encode($lab);
結果是:
Array ( [latitude] => [longitude] => ) {"repartition":[{"latLng":[{"latitude":null,"longitude":null}],"name":"Paris","code":"FR-75"},{"latLng":[{"latitude":null,"longitude":null}],"name":"Grenoble","code":"FR-38"}]}
緯度應該是:
$lab = array(
"repartition" => array(
array(
"latLng" => array( 2.347, 48.859 ),
"name" => "Paris",
"code" => "FR-75"
),
array(
"latLng" => array( 5.7243, 45.182081 ),
"name" => "Grenoble",
"code" => "FR-38"
)
)
);
像那樣:
{"repartition":[{"latLng":[2.347,48.859],"name":"Paris","code":"FR-75"}
如何從此函式中檢索緯度和經度以及如何在 $lab 陣列中檢索它?..
謝謝你的幫助。
uj5u.com熱心網友回復:
您忘記使用file_get_contents()(json_decode()不能單獨執行此操作)呼叫外部 API 。在你的 $lab 宣告中,你不需要把結果放在額外的陣列中,結果已經是一個陣列。
<?php
function extractLatLngFromAdd($address)
{
$geodata = file_get_contents('https://api-adresse.data.gouv.fr/search/?q=' . $address);
$geodata = json_decode($geodata);
// extract latitude and longitude
$result['latitude'] = $geodata->features[0]->geometry->coordinates[1];
$result['longitude'] = $geodata->features[0]->geometry->coordinates[0];
return $result;
}
$lab = array(
"repartition" => array(
array(
"latLng" => extractLatLngFromAdd('Paris'),
"name" => "Paris",
"code" => "FR-75"
),
array(
"latLng" => extractLatLngFromAdd('grenoble'),
"name" => "Grenoble",
"code" => "FR-38"
)
)
);
print_r($lab);
給出:
Array
(
[repartition] => Array
(
[0] => Array
(
[latLng] => Array
(
[latitude] => 48.859
[longitude] => 2.347
)
[name] => Paris
[code] => FR-75
)
[1] => Array
(
[latLng] => Array
(
[latitude] => 45.182081
[longitude] => 5.7243
)
[name] => Grenoble
[code] => FR-38
)
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/394880.html
下一篇:如何激活點擊以路由到谷歌地圖
