如何使用select过滤一个数组中的Google Maps标记?

时间:2014-03-11 10:33:40

标签: arrays google-maps google-maps-api-3 drop-down-menu google-maps-markers

我在我的网站上使用一个数组实现了谷歌地图,如下所示:

var gmarkers1 = [];
var markers1 = [];

markers1 = [
['0', 'Title', 52.4357808, 4.991315699999973],
['1', 'Title', 52.4357808, 4.991315699999973],
['2', 'Title', 52.4555687, 5.039231599999994],
];

在这个例子中有3个标记,但实际上还有更多。为了我的目的,这是唯一的方法(一个数组)。

问题:我希望能够使用选择框在此数组中进行过滤。因此,用户从选择中选择“汽车”,而Google地图仅显示带有属性(?)“汽车”的标记。

标记显示如下:

for (i = 0; i < markers1.length; i++) {
    var category;
    var pos = new google.maps.LatLng(markers1[i][2], markers1[i][3]);
    var content = markers1[i][1];
    bounds.extend(pos);
    marker1 = new google.maps.Marker({
        position: pos,
        map: map,
        icon: image1
    });

    gmarkers1.push(marker1);
    // [START]-Event listener to center view and go to position
    google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
        return function() {
          console.log('Gmarker 1 gets pushed')
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(15);
        }
    })(marker1, content));
}
enter code here

提前致谢。

2 个答案:

答案 0 :(得分:12)

您应该添加类别作为标记属性。

markers1 = [
    ['0', 'Title 1', 52.4357808, 4.991315699999973, 'car'],
    ['1', 'Title 2', 52.4357808, 4.981315699999973, 'third'],
    ['2', 'Title 3', 52.4555687, 5.039231599999994, 'car'],
    ['3', 'Title 4', 52.4555687, 5.029231599999994, 'second']
];

创建标记。标记是对象,因此将类别添加为属性。

var category = markers1[i][4];
var pos = new google.maps.LatLng(markers1[i][2], markers1[i][3]);
marker1 = new google.maps.Marker({
    position: pos,
    map: map,
    category: category,
    icon: image1
});

在选择更改时,调用函数检查类别是否与所选类别相同。

/**
 * Function to filter markers by category
 */

filterMarkers = function(category)
{
   for (i = 0; i < gmarkers1.length; i++) {
      marker = gmarkers1[i];

      // If is same category or category not picked
      if(marker.category == category || category.length == 0)
      {
          marker.setVisible(true);
      }
      // Categories don't match 
      else
      {          
          marker.setVisible(false);
      }
    }  
}

工作示例

&#13;
&#13;
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
    content: ''
});

// Our markers
markers1 = [
    ['0', 'Title 1', 52.4357808, 4.991315699999973, 'car'],
    ['1', 'Title 2', 52.4357808, 4.981315699999973, 'third'],
    ['2', 'Title 3', 52.4555687, 5.039231599999994, 'car'],
    ['3', 'Title 4', 52.4555687, 5.029231599999994, 'second']
];

/**
 * Function to init map
 */

function initialize() {
    var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
    var mapOptions = {
        zoom: 12,
        center: center,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    for (i = 0; i < markers1.length; i++) {
        addMarker(markers1[i]);
    }
}

/**
 * Function to add marker to map
 */

function addMarker(marker) {
    var category = marker[4];
    var title = marker[1];
    var pos = new google.maps.LatLng(marker[2], marker[3]);
    var content = marker[1];

    marker1 = new google.maps.Marker({
        title: title,
        position: pos,
        category: category,
        map: map
    });

    gmarkers1.push(marker1);

    // Marker click listener
    google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
        return function () {
            console.log('Gmarker 1 gets pushed');
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(15);
        }
    })(marker1, content));
}

/**
 * Function to filter markers by category
 */

filterMarkers = function (category) {
    for (i = 0; i < gmarkers1.length; i++) {
        marker = gmarkers1[i];
        // If is same category or category not picked
        if (marker.category == category || category.length === 0) {
            marker.setVisible(true);
        }
        // Categories don't match 
        else {
            marker.setVisible(false);
        }
    }
}

// Init map
initialize();
&#13;
#map-canvas {
    width: 500px;
    height: 500px;
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true&language=ee&dummy=dummy.js"></script>
<div id="map-canvas"></div>
<select id="type" onchange="filterMarkers(this.value);">
    <option value="">Please select category</option>
    <option value="second">second</option>
    <option value="car">car</option>
    <option value="third">third</option>
</select>
&#13;
&#13;
&#13;


按标记

按多个类别过滤

编辑@Myoji评论

要在每个标记上使用多个类别,只需将其添加为array并在if上修改filterMarkers条件。

markers1 = [
    ['0', 'Title 1', 52.4357808, 4.991315699999973, ['car', 'second']],
    ['1', 'Title 2', 52.4357808, 4.981315699999973, ['third']],
    ['2', 'Title 3', 52.4555687, 5.039231599999994, ['car', 'third']],
    ['3', 'Title 4', 52.4555687, 5.029231599999994, ['second']]
];

filterMarkers将是

/**
 * Function to filter markers by category
 */

filterMarkers = function(category)
{
   for (i = 0; i < gmarkers1.length; i++) {
      marker = gmarkers1[i];

      // If is same category or category not picked
      if((typeof marker.category == 'object' && marker.category.indexOf(category) >= 0) || category.length == 0){
      {
          marker.setVisible(true);
      }
      // Categories don't match 
      else
      {          
          marker.setVisible(false);
      }
    }  
}

工作示例

&#13;
&#13;
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
    content: ''
});

// Our markers
markers1 = [
  ['0', 'Title 1', 52.4357808, 4.991315699999973, ['car', 'second']],
  ['1', 'Title 2', 52.4357808, 4.981315699999973, ['third']],
  ['2', 'Title 3', 52.4555687, 5.039231599999994, ['car', 'third']],
  ['3', 'Title 4', 52.4555687, 5.029231599999994, ['second']]
];

/**
 * Function to init map
 */

function initialize() {
    var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
    var mapOptions = {
        zoom: 12,
        center: center,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    for (i = 0; i < markers1.length; i++) {
        addMarker(markers1[i]);
    }
}

/**
 * Function to add marker to map
 */

function addMarker(marker) {
    var category = marker[4];
    var title = marker[1];
    var pos = new google.maps.LatLng(marker[2], marker[3]);
    var content = marker[1];

    marker1 = new google.maps.Marker({
        title: title,
        position: pos,
        category: category,
        map: map
    });

    gmarkers1.push(marker1);

    // Marker click listener
    google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
        return function () {
            console.log('Gmarker 1 gets pushed');
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(15);
        }
    })(marker1, content));
}

/**
 * Function to filter markers by category
 */

filterMarkers = function (category) {
    for (i = 0; i < gmarkers1.length; i++) {
        marker = gmarkers1[i];
        // If is same category or category not picked
        if((typeof marker.category == 'object' && marker.category.indexOf(category) >= 0) || category.length == 0){
            marker.setVisible(true);
        }
        // Categories don't match 
        else {
            marker.setVisible(false);
        }
    }
}

// Init map
initialize();
&#13;
#map-canvas {
    width: 500px;
    height: 500px;
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true&language=ee&dummy=dummy.js"></script>
<div id="map-canvas"></div>
<select id="type" onchange="filterMarkers(this.value);">
    <option value="">Please select category</option>
    <option value="second">second</option>
    <option value="car">car</option>
    <option value="third">third</option>
</select>
&#13;
&#13;
&#13;


过滤后适合边界

编辑@bluantinoo评论

/**
 * Function to filter markers by category
 */

filterMarkers = function(category)
{
    var bounds = new google.maps.LatLngBounds();
    for (i = 0; i < gmarkers1.length; i++) {
        marker = gmarkers1[i];

        // If is same category or category not picked
        if(marker.category == category || category.length == 0)
        {
            marker.setVisible(true);
            bounds.extend(marker.getPosition());
        }
        // Categories don't match 
        else
        {          
            marker.setVisible(false);
        }
        map.fitBounds(bounds);
    }  
}

工作示例

&#13;
&#13;
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
    content: ''
});

// Our markers
markers1 = [
    ['0', 'Title 1', 52.4357808, 4.991315699999973, 'car'],
    ['1', 'Title 2', 52.4357808, 4.981315699999973, 'third'],
    ['2', 'Title 3', 52.4555687, 5.039231599999994, 'car'],
    ['3', 'Title 4', 52.4555687, 5.029231599999994, 'second']
];

/**
 * Function to init map
 */

function initialize() {
    var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
    var mapOptions = {
        zoom: 12,
        center: center,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    for (i = 0; i < markers1.length; i++) {
        addMarker(markers1[i]);
    }
}

/**
 * Function to add marker to map
 */

function addMarker(marker) {
    var category = marker[4];
    var title = marker[1];
    var pos = new google.maps.LatLng(marker[2], marker[3]);
    var content = marker[1];

    marker1 = new google.maps.Marker({
        title: title,
        position: pos,
        category: category,
        map: map
    });

    gmarkers1.push(marker1);

    // Marker click listener
    google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
        return function () {
            console.log('Gmarker 1 gets pushed');
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(15);
        }
    })(marker1, content));
}

/**
 * Function to filter markers by category
 */

filterMarkers = function(category)
{
    var bounds = new google.maps.LatLngBounds();
    for (i = 0; i < gmarkers1.length; i++) {
        marker = gmarkers1[i];

        // If is same category or category not picked
        if(marker.category == category || category.length == 0)
        {
            marker.setVisible(true);
            bounds.extend(marker.getPosition());
        }
        // Categories don't match 
        else
        {          
            marker.setVisible(false);
        }
        map.fitBounds(bounds);
    }  
}

// Init map
initialize();
&#13;
#map-canvas {
    width: 500px;
    height: 500px;
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true&language=ee&dummy=dummy.js"></script>
<div id="map-canvas"></div>
<select id="type" onchange="filterMarkers(this.value);">
    <option value="">Please select category</option>
    <option value="second">second</option>
    <option value="car">car</option>
    <option value="third">third</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

在@Rene Korss解决方案的基础上,这里是基于复选框的多重选择过滤器,但可以很容易地成为多个选择列表 - 只需获取要与之比较的选项名称的数组。

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
  content: ''
});
// Our markers
markers1 = [
  ['0', 'Title 1', 52.4357808, 4.991315699999973, ['car', 'second']],
  ['1', 'Title 2', 52.4357808, 4.981315699999973, ['third']],
  ['2', 'Title 3', 52.4555687, 5.039231599999994, ['car', 'third']],
  ['3', 'Title 4', 52.4555687, 5.029231599999994, ['second']]
];
markerCount = markers1.length
// Function to init map
function initialize() {
  var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
  var mapOptions = {
    zoom: 12,
    center: center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  for (i = 0; i < markerCount; i++) {
    addMarker(markers1[i]);
  }
}
// Function to add marker to map
function addMarker(marker) {
  var category = marker[4];
  var title = marker[1];
  var pos = new google.maps.LatLng(marker[2], marker[3]);
  var content = marker[1];

  marker1 = new google.maps.Marker({
    title: title,
    position: pos,
    category: category,
    map: map
  });

  gmarkers1.push(marker1);

  // Marker click listener
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
    return function() {
      console.log('Gmarker 1 gets pushed');
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
      map.setZoom(15);
    }
  })(marker1, content));
}
// Function on Change of checkbox
updateView = function(element) {
  if (element) {
    //Get array with names of the checked boxes
    checkedBoxes = ([...document.querySelectorAll('input[type=checkbox]:checked')]).map(function(o) {
      return o.id;
    });
    console.log(checkedBoxes);
    for (i = 0; i < markerCount; i++) {
      marker = gmarkers1[i];
      console.log(marker.category)
      //Filter to show any markets containing ALL of the selected options
      if (typeof marker.category == 'object' && checkedBoxes.every(function(o) {
          return (marker.category).indexOf(o) >= 0;
        })) {
        marker.setVisible(true);
      } else {
        marker.setVisible(false);
      }
    }
  } else {
    console.log('No param given');
  }
}
// Init map
initialize();
#map-canvas {
  width: 500px;
  height: 500px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3&language=ee&dummy=dummy.js"></script>
<div id="map-canvas"></div>
<div id="options">
  <input type="checkbox" id="car" onchange="updateView(this);" /> Car
  <input type="checkbox" id="second" onchange="updateView(this);" /> Second
  <input type="checkbox" id="third" onchange="updateView(this);" /> Third
</div>

基本上,你只需要一个包含所选复选框id的名称的数组:

checkedBoxes = ([...document.querySelectorAll('input[type=checkbox]:checked')]).map(function(o) { return o.id; });

然后比较每个位置类别并显示它是否包含所有选中的复选框,但可能有更多未选中。如果未选择任何一个,则显示所有内容:

if(typeof marker.category == 'object' && checkedBoxes.every(function (o) {return (marker.category).indexOf(o) >= 0;})){
      marker.setVisible(true);
}
else {
      marker.setVisible(false);
}

这也是JSfiddle

更新:根据评论请求,此处的代码段除非您检查某些内容,否则不会显示任何内容。此外,逻辑是您需要选择与标记完全相同的类别才能显示。

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
  content: ''
});
// Our markers
markers1 = [
  ['0', 'Title 1', 52.4357808, 4.991315699999973, ['car', 'second']],
  ['1', 'Title 2', 52.4357808, 4.981315699999973, ['third']],
  ['2', 'Title 3', 52.4555687, 5.039231599999994, ['third', 'car']],
  ['3', 'Title 4', 52.4555687, 5.029231599999994, ['second']]
];
markerCount = markers1.length
// Function to init map
function initialize() {
  var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
  var mapOptions = {
    zoom: 12,
    center: center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  for (i = 0; i < markerCount; i++) {
    addMarker(markers1[i]);
  }
}
// Function to add marker to map
function addMarker(marker) {
  var category = marker[4];
  var title = marker[1];
  var pos = new google.maps.LatLng(marker[2], marker[3]);
  var content = marker[1];

  marker1 = new google.maps.Marker({
    title: title,
    position: pos,
    category: category,
    map: map
  });

  gmarkers1.push(marker1);

  // Marker click listener
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
    return function() {
      console.log('Gmarker 1 gets pushed');
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
      map.setZoom(15);
    }
  })(marker1, content));
}
// Function on Change of checkbox
updateView = function(element) {
  if (element) {
    //Get array with names of the checked boxes
    checkedBoxes = ([...document.querySelectorAll('input[type=checkbox]:checked')]).map(function(o) {
      return o.id;
    });
    console.log(checkedBoxes);
    for (i = 0; i < markerCount; i++) {
      marker = gmarkers1[i];
      console.log(marker.category)
      //Filter to show any markets containing ALL of the selected options
      if(typeof marker.category == 'object' && marker.category.length === checkedBoxes.length && checkedBoxes.reduce((a, b) => a && marker.category.includes(b), true)){
        marker.setVisible(true);
      } else {
        marker.setVisible(false);
      }
    }
  } else {
    console.log('No param given');
  }
}
// Init map
initialize();
#map-canvas {
  width: 500px;
  height: 500px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3&language=ee&dummy=dummy.js"></script>
<div id="map-canvas"></div>
<div id="options">
  <input type="checkbox" id="car" onchange="updateView(this);" /> Car
  <input type="checkbox" id="second" onchange="updateView(this);" /> Second
  <input type="checkbox" id="third" onchange="updateView(this);" /> Third
</div>

JSfiddle