Я использовал это руководство от Google для создания веб-приложения, которое находит ближайший магазин из указанного пользователем местоположения:
http://code.google.com/apis/maps/articles/phpsqlsearch_v3.html
У меня мое приложение почти работает так, как я хочу, при загрузке страницы карта загружается, центрируется и устанавливается на уровень масштабирования 6, а пользователь заполняет форму своим местоположением.
Затем приложение извлекает всю информацию о магазине из базы данных и заполняет карту маркером для каждого из них.
Уровень масштабирования, похоже, тоже уменьшается, но я нигде не могу найти этого в коде.
На самом деле я хочу сделать при отправке увеличивать масштаб до уровня 6 и центрировать карту по широте и долготе введенного пользователем местоположения и выводить информацию о ближайших магазинах, например, о ближайших 5. Мне было интересно, есть ли кто-нибудь здесь знал, как реализовать эту функцию?
index.php
phpsqlsearch_genxml.php
createElement("markers");
$parnode = $dom->appendChild($node);
// Select all the rows in the markers table
$query = 'SELECT address1, address2, address3, longitude, latitude, name, town, store_id, postcode, storenumber
FROM uk_store
WHERE isActive=1 ';
if($_GET["region"] != '') {
$query .= ' AND region = "' . $_GET["region"] . '"';
} else {
$query .= ' AND region in("Scotland", "England", "Wales", "Northern Ireland") ';
}
// lets start to check what has been search on
if($_GET['postcode'] != '') {
//lets make sure postcode only has numbers letter and spaces
$searchparams .= 'postcode=' . $_GET['postcode'] . '&';
$postcode = $_GET['postcode'];
$postcode = verifyInput($postcode);
$query .= " AND postcode = '" . $postcode . "'";
}
if($_GET['town'] != '') {
// make sure town only has letters or spaces.
$searchparams .= 'town=' . $_GET['town'] . '&';
$town = $_GET['town'];
$town = verifyInput($town);
$query .= " AND town = '" . $town . "'";
}
if($_GET['min_lat'] && $_GET['min_long'] && $_GET['max_lat'] && $_GET['max_long'] ) {
$query .= " AND latitude BETWEEN " . $_GET['min_lat'] . " AND " . $_GET['max_lat'] . " AND longitude BETWEEN " . $_GET['min_long'] . " AND " . $_GET['max_long'] ;
$mapsearch = 1;
}
if(!($_GET['postcodeLat'] && $_GET['postcodeLong'])) {
$query .= " ORDER BY Region, Town , Name ";
}
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
header("Content-type: text/xml");
echo '';
if($_GET['postcodeLat'] && $_GET['postcodeLong'])
{
$count = 0;
// we need to sort the results by distance
while ($row = @mysql_fetch_array($result, MYSQL_ASSOC))
{
$address = $row['address1'] . ' ' . $row['address2'] . ' ' . $row['address3'];
$distance = distance($_GET['postcodeLat'], $_GET['postcodeLong'], $row['latitude'], $row['longitude']);
$row['distance'] = number_format($distance, 2);
$row['fname'] = $row['town'] . '-' . $row['name'];
$row['fname'] = str_replace("'",'', $row['fname']);
$row['fname'] = ereg_replace(' ','-', $row['fname']);
$row['fname'] = ereg_replace('\/','-', $row['fname']);
$row['fname'] = ereg_replace('\(','', $row['fname']);
$row['fname'] = ereg_replace('\)','', $row['fname']);
$row['fname'] = strtolower($row['fname']);
//get distance and add to $row array
$results[$distance.$row['id']] = $row;
}
ksort($results);
foreach ($results as $key => $row)
{
// ADD TO XML DOCUMENT NODE
$address = $row['address1'] . ' ' . $row['address2'] . ' ' . $row['address3'];
echo ' ';
}
}
else
{
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result))
{
$address = $row['address1'] . ' ' . $row['address2'] . ' ' . $row['address3'];
$row['fname'] = $row['town'] . '-' . $row['name'];
$row['fname'] = ereg_replace(' ','-', $row['fname']);
$row['fname'] = ereg_replace('\/','-', $row['fname']);
$row['fname'] = ereg_replace('\(','', $row['fname']);
$row['fname'] = ereg_replace('\)','', $row['fname']);
// ADD TO XML DOCUMENT NODE
echo ' ';
}
}
// End XML file
echo ' ';
// make sure the data is xml friendly
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
//$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// calculate the distance in miles or kms between any two points
function distance($lat1, $lon1, $lat2, $lon2, $unit = '') {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
if($unit != '')
{
$unit = strtoupper($unit);
}
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
function VerifyInput ($input, $forceInt = false) {
if (is_numeric($input)) {
return $input;
} elseif (!$forceInt) {
if (get_magic_quotes_gpc() && trim(ini_get("magic_quotes_sybase")) == "") {
$input = stripslashes($input);
$input = str_replace("'", "", $input);
$input = str_replace("`", "", $input);
} elseif (!get_magic_quotes_gpc()) {
$input = str_replace("'", "", $input);
$input = str_replace("`", "", $input);
}
return $input;
} elseif ($forceInt) {
return 0;
}
}
?>
Извините, здесь много вставок, но я подумал, что лучше включить все, чем рисковать, что кто-то не сможет ответить, потому что там не хватало деталей.
ОБНОВЛЕНИЕ
Я попытался вставить этот фрагмент кода в функцию searchLocations
, но, похоже, это никак не повлияло на поведение:
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
/////////////// new code
var myOptions = {
zoom: 11,
center: address.geometry.location,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
////////////////
} else {
alert(address + ' not found');
}
});
}