为 xml GOOGLE MAPS 生成的每个标记创建复选框

Creating check boxes for each markers generated by xml GOOGLE MAPS

我已经有了一张工作地图,它可以生成有效的 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);
  });       
}

我的 createMarker()

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 边界上。是否可以在循环中插入它?

好的

与复选框无关的所有内容,我都忽略了。你必须把它放回你的代码中。 我写了一个功能示例,你可以copy/paste按原样。

<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 进行通信。 它给你(某种程度上)你的问题的组合; 我的数据库上有一个不同的 table,但这应该不是问题。 我添加 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');

index.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>

ajax.php

<?php
$link = mysqli_connect('localhost', 'root', '', 'Whosebug');  /* 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;
?>

您可以添加 links/buttons,例如

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

要添加客户的职位,请在此处查看我的回答 google getLocation function not work in my script