Я делаю карту Google, которая получает свои данные из базы данных MySQL.Я изменил пример кода на «Использование MySQL и PHP с Google Maps» У меня есть php-файл markerxml.php, который возвращает записи в формате XML при отправке ему категории, например: markerxml.php?category_select=Bars
.
У меня есть выборка, которая получает Категории из базы данных и заполняет ее.Я попытался onchange='category_select(this)
выбрать для функции category_select здесь:
function category_select(obj){
var urlString = "http://example.com/markerxml.php?category_select=";
var category_select = obj.options[obj.selectedIndex];
if (category_select.value != "nothing"){
window.location=urlString + category_select.value;
}
}
Затем, когда карта создана, есть downloadUrl(category_select, function(doc)
(я попытался поместить туда значение category_select)
Если я обойду свой избранный и просто жесткий код: downloadUrl('markerxml.php?category_select=Bars', function(doc)
, тогда я получу свою карту с маркерами.
Вот код в файле карты:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Using MySQL and PHP with 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>
<?php
$conn = new mysqli("localhost","","","") or die($this->mysqli->error);
$result = $conn->query("select DISTINCT Bus_categories from cmsb_markers ORDER BY Bus_categories ASC");
echo "<form action='markerxml.php' method='get' >";
echo "<select style='font-size:14px;height:20px;' name='category_select' onchange='category_select(this)'>";
echo "<option value=''selected>Select Business Category</option>";
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['Bus_categories'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
echo "</select></form>"; ?>
<div id="map"></div>
<script>
var customLabel = {
restaurant: {
label: 'R'
},
bar: {
label: 'B'
}
};
function category_select(obj){
var urlString = "http://example.com/markerxml.php?category_select=";
var category_select = obj.options[obj.selectedIndex];
if (category_select.value != "nothing"){
window.location=urlString + category_select.value;
}
}
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(39.1,-94.55),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl('markerxml.php?category_select=Bars', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name1');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
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, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<My API key>&callback=initMap">
</script>
</body>
</html>
Вывод файла markerxml.php, просматриваемого в браузере с использованием источника представления (одна запись):
<?xml version="1.0"?>
<markers><marker id="452" Bus_categories="Bars" name1="PBR Big Sky" address="111 E 13th St." phone="(816) 442-8145" Contact="Will Kinser" City="Kansas City" state="MO" zip="64105" email="info@pbrbigskykc.com" web="www.pbrbigskykc.com" lat="39.098391" lng="-94.581677" distance="2.4730047851899717"/></markers>
Вот код для markerxml.php:
<?php
require("phpsqlsearch_dbinfo.php");
// Get parameters from URL
$center_lat = 39.125212;
$center_lng = -94.551136;
$radius = 10;
// 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=mysql_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 *, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM cmsb_markers WHERE Bus_categories = '$_GET[category_select]' HAVING distance < '%s' ORDER BY distance LIMIT 0 , 1838",
mysql_real_escape_string($center_lat),
mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$result = mysql_query($query);
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("id", $row['id']);
$newnode->setAttribute("Bus_categories", $row['Bus_categories']);
$newnode->setAttribute("name1", $row['name1']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("phone", $row['Bus_phone']);
$newnode->setAttribute("Contact", $row['content']);
$newnode->setAttribute("City", $row['Bus_city']);
$newnode->setAttribute("state", $row['Bus_state']);
$newnode->setAttribute("zip", $row['Bus_zip']);
$newnode->setAttribute("email", $row['Bus_email']);
$newnode->setAttribute("web", $row['Bus_web']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
echo $dom->saveXML();
?>
Вот HTML-кодвывод выбора:
<form action='markerxml.php' method='get' >
<select style='font-size:14px;height:20px;' name='category_select' onchange='category_select(this)'>
<option value=''selected>Select Business Category</option>
<option value=""></option>
<option value="Accountants">Accountants</option>
<option value="Accountants--Certified Public">Accountants--Certified Public</option>
<option value="Accounting & Tax Service">Accounting & Tax Service</option>
<option value="Accounting Software">Accounting Software</option><option value="Advertising">Advertising</option>
<option value="Advertising Agencies & Counselors">Advertising Agencies & Counselors</option>
<option value="Advertising--Outdoor">Advertising--Outdoor</option>
<option value="Agricultural Fertilizer & Chemicals">Agricultural Fertilizer & Chemicals</option>
<option value="Air Conditioning & Heating Sales & Service">Air Conditioning & Heating Sales & Service</option>
</select>
</form>
<div id="map"></div>