[英]Php to echo returned value from javascript function
我正在使用函数getAddress()
来获取所提供坐标的地址。 如何确保函数的返回值可以在php中回显?
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=yourAPIkey"></script>
<script type="text/javascript">
function GetAddress(lat,lng) {
var lat = parseFloat(lat);
var lng = parseFloat(lng);
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var addr = results[0].formatted_address;
return addr;
}
}
});
}
</script>
<?php
$lng = 103.72;
$lat = 1.34628;
echo "<script type='text/javascript'>",
"GetAddress(",$lat,",",$lng,");",
"</script>";
?>
</html>
该echo
,你已经将呼应JS脚本到你的页面,而不是结果,所以我建议你加那么结果容器把里面的数据是这样的:
<?php
$lng = 103.72;
$lat = 1.34628;
echo "<p id='result'> </p>";
echo "<script type='text/javascript'>".
"document.getElementById('result').innerText = GetAddress(".$lat.",".$lng.");".
"</script>";
?>
希望这可以帮助。
如果您要做的只是写函数调用的输出(根据您最近的评论回复),则可以执行以下操作:
$lng = 103.72;
$lat = 1.34628;
echo "<script type='text/javascript'>document.write(GetAddress(",$lat,",",$lng,"));</script>";
因此,无论在GetAddress
调用GetAddress
,您都将看到输出。
另外,如果您需要定位要显示结果的特定区域,请参阅Zakaria Acharki
更新的答案。
我个人会避免将php和javascript混合使用,而只是在php中做所有事情。
例如;
<?php
// Config
define('API_KEY', 'yourAPIkey');
// Helper function to geodecode lat/lng
function getFormattedAddress($lat, $lng) {
$result = json_decode(file_get_contents("https://maps.google.com/maps/api/geocode/json?key=". API_KEY ."&latlng=$lat,$lng"));
if ($result->status == 'OK') {
return $result->results[0]->formatted_address;
}
return 'Invalid lat/lng coordinates';
}
// Usage
$lat = 40.714224;
$lng = -73.961452;
echo getFormattedAddress($lat, $lng);
?>
产出: 277 Bedford Ave, Brooklyn, NY 11211, USA
因此,您的php脚本具有lat
, lng
坐标,因此您可以调用php函数并一次性渲染结果。
PS:您应该避免在问题中发布API密钥; 人们可能会滥用它;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.