我按照google教程创建了一个商店定位器:https://developers.google.com/maps/solutions/store-locator/clothing-store-locator
我试图在显示器上显示错误,但我没有得到任何东西,唯一的积极的事情是创建静态标记出现在屏幕上,动机是api键实现是正确的。
不幸的是,我无法理解与数据库缺乏通信的原因。
我可以使用哪种功能,以便能够更清楚地了解工作的情况?
索引.html:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE html >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Creating a Store Locator on Google Maps</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body style="margin:0px; padding:0px;">
<div>
<label for="raddressInput">Search location:</label>
<input type="text" id="addressInput" size="15"/>
<label for="radiusSelect">Radius:</label>
<select id="radiusSelect" label="Radius">
<option value="50" selected>50 kms</option>
<option value="30">30 kms</option>
<option value="20">20 kms</option>
<option value="10">10 kms</option>
</select>
<input type="button" id="searchButton" value="Search"/>
</div>
<div><select id="locationSelect" style="width: 10%; visibility: hidden"></select></div>
<div id="map" style="width: 100%; height: 90%"></div>
<script>
var map;
var markers = [];
var infoWindow;
var locationSelect;
// Initialize and add the map
function initMap() {
// The location of Uluru
var uluru = {lat: -25.344, lng: 131.036};
// The map, centered at Uluru
map = new google.maps.Map(document.getElementById('map'), {zoom: 4,
center: uluru,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
// The marker, positioned at Uluru
var marker = new google.maps.Marker({position: uluru, map: map});
infoWindow = new google.maps.InfoWindow();
searchButton = document.getElementById("searchButton").onclick = searchLocations;
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
</script>
<script type="text/javascript">
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);
} else {
alert(address + ' not found');
}
});
}
function downloadUrl(url,callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var id = markerNodes[i].getAttribute("id");
var name = markerNodes[i].getAttribute("name");
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name;
locationSelect.appendChild(option);
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
locationSelect.style.visibility = "visible";
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str);
}
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCbn9gIka8i-33HotlIor7GHMt2WEo_aAQ&callback=initMap">
</script>
</body>
</html>
phpsqlsearch\u dbinfo.php:
<?php
$username="root";
$password="root";
$database="ca2solution";
?>
storelocator.php
<?php
require("phpsqlsearch_dbinfo.php");
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysqli_connect ("localhost", $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT id, name, address, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
real_escape_string($center_lat),
real_escape_string($center_lng),
real_escape_string($center_lat),
real_escape_string($radius));
$result = mysqli_query($connection, $query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = mysqli_num_rows($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("id", $row['id']);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
echo $dom->saveXML();
?>
1条答案
按热度按时间fafcakar1#
我注意到原始代码中有一些不正确的地方(使用
mysql
,中出错parseXml
,一个未使用的搜索框和。。。其他人)所以,我有一点业余时间,我有一个发挥,并提出了一个有点不同的版本,如果研究和改编,应该有助于解决所面临的问题。相同结构的示例表。。。。。。
数据示例。。。。。。。
一个mysql
Stored Procedure
我以前写过-为了适应这个特殊的问题而做了一些小的修改。生成的xml示例(当然取决于数据库)
为了简单起见,php和html组合成一个页面进行测试。在php中处理用户提供的数据和数据库访问时的最佳实践是使用
prepared statement
,以避免sql注入攻击。下面的代码使用PDO
对于数据库层,但是可以很容易地用mysqli
.本例中的sql本身被编写为
stored procedure
(如上所示),Map的初始视口以苏格兰为中心,而不是澳大利亚,因为我的数据库主要包含所示区域内和周围的位置。我在javascript中发现了几个小错误,但幸运的是在这里纠正了这些错误。