为xml谷歌地图生成的每个标记创建复选框

Creating check boxes for each markers generated by xml GOOGLE MAPS

本文关键字:创建 复选框 xml 谷歌地图      更新时间:2023-09-26

我已经有一个工作地图,它可以生成有效的xml,并且可以在我的地图上生成标记。现在我想做的是在为 xml 中的每个循环生成映射时,我可以为每个名称异步创建一个复选框。下面是生成 XML 的代码

function searchNearLocations(radius){
clearLocations();
 var searchUrl = './designIncludes/phpLogicIncludes/searchMarkers.php?lat=' + userLat +'&lng=' + userLng + '&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 info = markerNodes[i].getAttribute("info");
     var tts = markerNodes[i].getAttribute("tts");
     var latlng = new google.maps.LatLng(
          parseFloat(markerNodes[i].getAttribute("lat")),
          parseFloat(markerNodes[i].getAttribute("lng")));
     createMarker(latlng, name, address,info,tts);
     createCheckboxes(name);
     bounds.extend(latlng);
   }
   map.fitBounds(bounds);
  });       
}

我的创建标记()

function createMarker(latlng, name, address,info,tts) {
  var html = "<b>" + name + "</b></br><u>" + address + "</u></br>" + info + "</br>" + "Time allowance to spend: " + tts;
  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);
}

我在javascript方面不是那么好,但我有一个marker=[]数组全局变量。我可以使用该变量生成一个复选框吗?顺便说一下,在调用 searchNearLocations 函数之前,我还有一个预制的标记,我想将其添加到 latlng 边界上。是否可以将其插入循环中?

好的

与复选框无关的一切,我都忽略了。 您必须将其放回代码中。我写了一个功能示例,您可以按原样复制/粘贴它。

<script src="http://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript">
var markers = [];
var map;
/* I don't have that XML.  I'll just insert a few locations hard coded.  You can ignore this; it doesn't affect your question  */
var markerNodes = [
  {latlng: new google.maps.LatLng(50.896328544032805,4.4825010816688), name: 'Brussels Airport', address: 'A201, 1930 Zaventem', info: 'National airport of Brussels', tts: 'foo'},
  {latlng: new google.maps.LatLng(50.8957080950929,4.334064952575659), name: 'Football stadion', address: 'Marathonlaan', info: 'Football stadion of the Red Devils', tts: 'foo'},
  {latlng: new google.maps.LatLng(50.82302545625156,4.39255052014533), name: 'VUB campus', address: 'Pleinlaan 2', info: 'University of Brussels', tts: 'foo'}
];
function initialize() {
  var position = new google.maps.LatLng(50.84499325563654,4.349978498661017);
  var myOptions = {
    zoom: 11,
    center: position
  };
  map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
  searchNearLocations(null);  // I ignore the radius part.  I presume this searches for locations in a DB, or something... 
}
/* never mind most of the changes I made here, it's just to ignore the xml part of the code */
function searchNearLocations(radius) {
  clearLocations();
  var bounds = new google.maps.LatLngBounds();
  for (var i=0; i<markerNodes.length; i++) {
    var latlng = markerNodes[i].latlng,
         name = markerNodes[i].name,
         address =  markerNodes[i].address,
         info = markerNodes[i].info,
         tts = markerNodes[i].tts;
    createMarker(latlng, name, address, info, tts);
    createCheckbox(name, i);  // the most important thing is to pass the i; then markers[i] corresponds with checkboxes[i]
    bounds.extend(latlng);
  }
  map.fitBounds(bounds);
}
function createMarker(latlng, name, address, info, tts) {
  // var html = "<b>" + name + "</b></br><u>" + address + "</u></br>" + info + "</br>" + "Time allowance to spend: " + tts;
  var marker = new google.maps.Marker({
    map: map,
    title: name,     // You should add this
    position: latlng
  });
  google.maps.event.addListener(marker, 'click', function() {
    /* I'll ignore the infoWindow  */
  });
  markers.push(marker);
}
function clearLocations() {
  for (var i=0; i<markers.length; i++) {
    markers[i].setMap(null);
  }
  markers=[];
}
function checkboxChanged(i, checked) {
  if(checked) {
    markers[i].setMap(map);
  }
  else {
    markers[i].setMap(null);
  }
}
function createCheckbox(name, i) {
  document.getElementById('checkboxes').innerHTML += 
    '<input type="checkbox" checked="checked" onclick="checkboxChanged(' + i + ', this.checked);"> ' + name + '<br>';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas {
  width: 500px;
  height: 400px;
}
</style>
<div id="map-canvas"></div>
<div id="checkboxes"></div>

你能设法将其包含在你的代码中吗?


编辑:下面是数据库中的位置示例;我绕过 xml 并通过 JSON 进行通信。它为您提供了(某种)问题的组合;我的数据库上有一个不同的表,但这应该不是问题。我添加jQuery,只是为了ajax。

CREATE TABLE IF NOT EXISTS stations (
  id bigint(15) NOT NULL AUTO_INCREMENT,
  lat decimal(12,10) DEFAULT NULL,
  lng decimal(12,10) DEFAULT NULL,
  name varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
INSERT INTO stations (id, lat, lng, name) VALUES
(1, '50.8456035000', '4.3568658000', 'Brussel-Centraal'),
(2, '50.8413140000', '4.3490830000', 'Brussel-Kapellekerk'),
(3, '50.8517507000', '4.3623635000', 'Brussel-Congres'),
(4, '50.8604931000', '4.3607035000', 'Brussel-Noord'),
(5, '50.8348278000', '4.3365303000', 'Brussel-Zuid');

索引.php

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript">
var markers = [];
var map;
// settings, to pass to the DB
var lat = 50.84499325563654;
var lng = 4.349978498661017;
var radius = 1.5;  /* set this to more than 1.5 to see more locations */
function initialize() {
  var position = new google.maps.LatLng(50.84499325563654, 4.349978498661017);
  var myOptions = {
    zoom: 11,
    center: position
  };
  map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
  searchNearLocations(lat, lng, radius);
}
function searchNearLocations(lat, lng, radius) {
  document.getElementById('checkboxes').innerHTML = '';
  // we start an Ajax call.  
  $.ajax({
    url: 'ajax.php',
    data: {lat: lat, lng: lng, radius: radius},
    dataType: 'json',
    success: function(data) {
      // the request has returned data.  Now we can proceed
      clearLocations();
      var bounds = new google.maps.LatLngBounds();
      for (var i=0; i<data.length; i++) {
        var latlng = new google.maps.LatLng(data[i].lat, data[i].lng),
             name = data[i].name;
             /* add what ever extra data you need */
        createMarker(latlng, name, null, null, null);
        createCheckbox(name, i);  // the most important thing is to pass the i; then markers[i] corresponds with checkboxes[i]
        bounds.extend(latlng);
      }
      map.fitBounds(bounds);
    }
  });
}
function createMarker(latlng, name, address, info, tts) {
  /* var html = "<b>" + name + "</b></br><u>" + address + "</u></br>" + info + "</br>" + "Time allowance to spend: " + tts;  */
  var marker = new google.maps.Marker({
    map: map,
    title: name,     // You should add this
    position: latlng
  });
  google.maps.event.addListener(marker, 'click', function() {
    /* I'll ignore the infoWindow  */
  });
  markers.push(marker);
}
function clearLocations() {
  for (var i=0; i<markers.length; i++) {
    markers[i].setMap(null);
  }
  markers=[];
}
function checkboxChanged(i, checked) {
  if(checked) {
    markers[i].setMap(map);
  }
  else {
    markers[i].setMap(null);
  }
}
function createCheckbox(name, i) {
  document.getElementById('checkboxes').innerHTML += 
    '<input type="checkbox" checked="checked" onclick="checkboxChanged(' + i + ', this.checked);"> ' + name + '<br>';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas {
  width: 500px;
  height: 400px;
}
</style>
<div id="map-canvas"></div>
<div id="checkboxes"></div>

阿贾克斯.php

<?php
$link = mysqli_connect('localhost', 'root', '', 'stackoverflow');  /* put your settings back */
if(!$link) {
  die ('unable to connect to the database' . mysqli_connect_error());
}
//Get parameters from URL
$myLat = (isset ($_GET['lat']) ? $_GET['lat'] : 0.0);  // give it some default
$myLng = (isset ($_GET['lng']) ? $_GET['lng'] : 0.0);
$calcDistance = (isset ($_GET['radius']) ? $_GET['radius'] : 1.0);
//Search the rows in the markers table
/* I have a slightly different table; I'll continue with mine; it's easy to put everything back */
// $query = sprintf("SELECT siteName,address,lat,lng,info,tts, (6371 * acos(cos(radians('%s')) * cos(radians(lat)) * cos(radians(lng) - radians ('%s')) + sin(radians('%s')) * sin(radians(lat))))AS distance FROM mapTable HAVING distance < '%s' ORDER BY distance LIMIT 0, 50",
$query = sprintf("SELECT id, lat, lng, name, (6371 * acos(cos(radians('%s')) * cos(radians(lat)) * cos(radians(lng) - radians ('%s')) + sin(radians('%s')) * sin(radians(lat)))) AS distance FROM stations HAVING distance < '%s' ORDER BY distance LIMIT 0, 50",
mysqli_real_escape_string($link, $myLat),
mysqli_real_escape_string($link, $myLng),
mysqli_real_escape_string($link,$myLat),
mysqli_real_escape_string($link, $calcDistance));
$result = mysqli_query($link, $query);
$row_cnt = mysqli_num_rows($result);
if(!$result) {
  die("Invalid query: " . mysqli_error());
}
header("content-type: application/json; charset=utf-8");
$items = array();
//iterate through the rows,
while($row = mysqli_fetch_assoc($result)) {
  $items[] = $row;
}
echo json_encode($items);  // this can immediatly be read by javascript
exit;
?>

您可以添加链接/按钮,例如

<div onclick="searchNearLocations(50.80, 4.35, 20)">click: 20 km radius from (50.80, 4.35)</div>

要添加客户的位置,请在此处查看我的答案谷歌获取位置函数在我的脚本中不起作用