gpt4 book ai didi

javascript - Google map api 从特定区域的数据库中搜索标记

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:48:59 25 4
gpt4 key购买 nike

我已经设置了从 mysql 数据库加载数据并显示标记的 google map API。我面临的问题是,无论我在搜索位置字段中输入什么,所有标记都会立即显示...... 我只想显示搜索到的区域和标记在那个区域。它不应该一次显示所有标记,而只显示搜索区域中的标记。

我的意思是我想将 map 缩放到搜索到的区域。目前,如果我只有一个标记 map 放大显示,但如果我有许多标记 map 缩小显示所有标记。这是我正在处理“http://funfeat.com/clients/gmap/gmap3.html”的 map ,现在我已经将标记设置得非常非常远, map 仍然通过缩小显示所有标记。

gmap.php 是提供来自mysql 数据库的xml 结果的文件。下面的代码是我用来显示 map 的代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var markers = [];
var infoWindow;
var locationSelect;

function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 10,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();

locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}

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 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);
}

function searchLocationsNear(center) {
clearLocations();

var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'gmap.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 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);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}

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 + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}

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 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, 'text/xml');
}
}

function doNothing() {}

//]]>
</script>
</head>

<body style="margin:0px; padding:0px;" onLoad="load()">
<div>
<input type="text" id="addressInput" size="10"/>
<select id="radiusSelect">
<option value="25" selected>25mi</option>
<option value="100">100mi</option>
<option value="200">200mi</option>
</select>

<input type="button" onClick="searchLocations()" value="Search"/>
</div>
<div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>
<div id="map" style="width: 100%; height: 80%"></div>
</body>
</html>

最佳答案

http://funfeat.com/clients/gmap/gmap.php?lat=47&lng=-122&radius=2生成有效的 XML 但您的查询一定是错误的。它拉出 10 个标记,其中 9 个是正确的,但第 10 个生成 <marker name="Pakistan" address="Chowk Azam, Layyah" lat="31.008364" lng="71.224342" type="cITY"/>这肯定不在坐标的 2 英里范围内。您的查询不应从数据库中获取最后一个标记。

由于不鼓励使用 mysql_ 函数,因此可以使用以下代码使用 PDO

//dependant on your setup
$host= "WWW";
$username="XXX";
$password="YYY";
$database="ZZZ";
// 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);
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Prepare statement
$stmt = $dbh->prepare("SELECT name, lat, lng, ( 3959 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance FROM gbstn HAVING distance < ? ORDER BY distance ASC LIMIT 0 , 20");
// Assign parameters
$stmt->bindParam(1,$center_lat);
$stmt->bindParam(2,$center_lng);
$stmt->bindParam(3,$center_lat);
$stmt->bindParam(4,$radius);
//Execute query
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();

EDIT 添加以在未找到记录时捕获错误

    if ($stmt->rowCount()==0) {
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", "No Records Found");
$newnode->setAttribute("lat", $center_lat);//Sends marker to search location
$newnode->setAttribute("lng", $center_lng);
$newnode->setAttribute("distance", 0);
}
else {

编辑结束

    // Iterate through the rows, adding XML nodes for each
while($row = $stmt->fetch()) {
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$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();

}


catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", gmap.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
//Close the connection
$dbh = null;

上面查询的部分HAVING distance < '%s'是应该清除最后一个标记的部分。

如果在搜索中未找到任何记录,我添加了错误捕获并将 map 发送到 lat/lng 0,0。参见 My Implementation Here

关于javascript - Google map api 从特定区域的数据库中搜索标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13551228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com