我有一个应用程序,它通过谷歌地图 api(距离矩阵和地图 API)使用地理定位来计算距离并在地图上显示图钉。我的逻辑存在性能问题(我的数据库中有 100 个地址,我将它们全部抓取,我将所有地址都放入距离矩阵并获取我所在位置的距离)每次用户点击时我都会这样做更新位置按钮。但是该方法有一个问题,每次单击刷新按钮时我都会发出 100 个请求,并且仅适用于 1 个用户。显然,有时 API 会限制每天的请求数。我的问题是:我怎样才能获得更好的性能并改进我的逻辑,让这个应用程序运行得更快并且不达到每日请求限制?我有大约 1000 人在使用这个应用程序。
这是我的代码:
<?php
header('Content-Type: application/json');
// Open the connection with the database
$conn = mysql_connect('localhost', 'gennovacap', 'coupons');
mysql_select_db('coupons', $conn);
$id_voucher = $_POST['id_voucher'];
$uuid = $_POST['uuid'];
// $uuid = "1343C38F-C0F3-4D86-B763-C14CFBF1DAC3";
// $id_voucher = 8;
$q = mysql_query("SELECT * FROM vouchers WHERE id_voucher = ".$id_voucher);
$voucher = mysql_fetch_assoc($q);
if(preg_match('/[\+]{2}+/', $voucher['address'])) {
$i = 0;
foreach(explode('++', $voucher['address']) as $address){
$address = preg_replace('/\s/m', '+', $address);
$request = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$result = simplexml_load_file($request);
$latitude = $result->result->geometry->location[0]->lat;
$longitude = $result->result->geometry->location[0]->lng;
$json['markers'][$i]['latitude'] = $latitude;
$json['markers'][$i]['longitude'] = $longitude;
$json['markers'][$i]['titlev'] = $voucher['name'];
$i++;
}
} else {
$address = preg_replace('/\s/m', '+', $voucher['address']);
$request = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$result = simplexml_load_file($request);
$latitude = $result->result->geometry->location[0]->lat;
$longitude = $result->result->geometry->location[0]->lng;
$json['markers'][0]['latitude'] = $latitude[0];
$json['markers'][0]['longitude'] = $longitude[0];
$json['markers'][0]['titlev'] = $voucher['name'];
}
// See if the user redeemed this coupon
$redemption = mysql_query("SELECT * FROM redemptions WHERE uuid = '".$uuid."' AND id_voucher = '".$id_voucher."'");
$count = mysql_num_rows($redemption);
if($count > 0) {
$created_at = mysql_fetch_row($redemption);
$json['titlev'] = $voucher['name'];
$json['deal'] = $voucher['deal'];
$json['redemptions'] = false;
$json['redemptions_text'] = $created_at[3];
} else {
$json['titlev'] = $voucher['name'];
$json['deal'] = $voucher['deal'];
$json['redemptions'] = true;
$json['redemptions_text'] = "Redeem This Coupon";
}
print json_encode($json);