Как да филтрирате свойства в json данни в Google Maps API v.3 с select?

Бих искал да филтрирам свойства в json данни в google maps api с select.

Видях няколко примера тук, но не намерих пример, който зарежда външен файл json и филтрира свойствата.

Тук работя върху пример за developers.google. Проблемът ми е във филтрите в java файла. Все още не съм намерил начин да направя това.

Искам да филтрирам магнитуда на земетресенията.

Може ли някой да ми помогне, моля?

Благодаря предварително

Вижте моля: http://jsfiddle.net/Alisson_BRA/9dzj49op/1/

Пълен JSON: https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js

JSON (пример), HTML и JS:

{
    "type": "FeatureCollection",
    "features": [{
            "type": "Feature",
            "properties": {
                "mag": 5.4,
                "place": "48km SSE of Pondaguitan, Philippines",
                "status": "AUTOMATIC" },
            "geometry": {
                "type": "Point",
                "coordinates": [126.3832, 5.9775] },
                },
                 {
             "type": "Feature",
             "properties": {
                "mag": 5.7,
                "place": "35km ESE of Ndoi Island, Fiji",
                "status": "REVIEWED" },
            "geometry": {
                "type": "Point",
                "coordinates": [-178.3725, -20.753] },
              },
            ]
}

<!DOCTYPE html> <html> <head> <style> <link rel="stylesheet" href="/bgstyle.css"> </style> </head> <body> <script> var gmarkers1 = []; var markers1 = []; var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 2, center: new google.maps.LatLng(2.8,-187.3), mapTypeId: 'terrain', streetViewControl: false, mapTypeControl: false }); var script = document.createElement('script'); script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js'; document.getElementsByTagName('head')[0].appendChild(script); } window.eqfeed_callback = function(results) { for (var i = 0; i < results.features.length; i++) { var coords = results.features[i].geometry.coordinates; var latLng = new google.maps.LatLng(coords[1],coords[0]); var marker = new google.maps.Marker({ position: latLng, map: map }); } } gmarkers1.push(marker1); // Function to filter markers by category filterMarkers = function (category) { for (i = 0; i < markers1.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); } } } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> </script> <div class="mapWrap"> <div id="map"></div> <div class="investCast"> <select id="mag" onchange="filterMarkers(this.value);"> <option value="">Selected the magnitude</option> <!-- value="4.5=<" Is this correct? I want to load all the values less or equal than 4.5 --> <option value="4.5=<">Less than or equal 4.5</option> <!-- value="4.6 to 4.9=<" Is this correct? I want to load all the values between 4.6 to 4.9 --> <option value="4.6 to 4.9">Between 4.6 and 4.9</option> <!-- value="4.6 to 4.9=<" Is this correct? I want to load all the values greater or equal 5 --> <option value=">=5">Greater than or equal 5</option> </select> </div> </div> </body> </html>

person Alisson    schedule 20.05.2018    source източник


Отговори (2)


Зареждате всички маркери на картата, за да започнете. Една от възможностите за филтрирането им е да добавите данните, по които искате да ги филтрирате, към маркера (като свойство):

for (var i = 0; i < results.features.length; i++) {
  var coords = results.features[i].geometry.coordinates;
  var latLng = new google.maps.LatLng(coords[1], coords[0]);

  //Creating a marker and putting it on the map, add magnitude as a "custom property"
  var marker = new google.maps.Marker({
    position: latLng,
    map: map,
    mag: results.features[i].properties.mag
  });
  gmarkers.push(marker);
}

След това филтрирайте маркерите по тази стойност:

// Function to filter markers by category
var filterMarkers = function(category) {
  switch (category) {
    case "4.5=<":
      for (i = 0; i < gmarkers.length; i++) {
        marker = gmarkers[i];
        // If is same category or category not picked
        if (marker.mag <= 4.5) {
          marker.setVisible(true);
        }
        // Categories don't match 
        else {
          marker.setVisible(false);
        }
      }
      break;
    case "4.6 to 4.9":
      for (i = 0; i < gmarkers.length; i++) {
        marker = gmarkers[i];
        // If is same category or category not picked
        if (4.6 <= marker.mag && marker.mag <= 4.5) {
          marker.setVisible(true);
        }
        // Categories don't match 
        else {
          marker.setVisible(false);
        }
      }
      break;
    case ">=5":
      for (i = 0; i < gmarkers.length; i++) {
        marker = gmarkers[i];
        // If is same category or category not picked
        if (5 <= marker.mag) {
          marker.setVisible(true);
        }
        // Categories don't match 
        else {
          marker.setVisible(false);
        }
      }
      break;
    default:
      for (i = 0; i < gmarkers.length; i++) {
        marker = gmarkers[i];
        marker.setVisible(true);
      }
  }
}

доказателство за концептуална цигулка

въведете описание на изображението тук

кодов фрагмент:

var gmarkers = [];
var markers = [];
var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 1,
    center: new google.maps.LatLng(30, 0),
    mapTypeId: 'terrain',
    streetViewControl: false,
    mapTypeControl: false
  });

  // Create a <script> tag and set the USGS URL as the source.
  var script = document.createElement('script');
  // This example uses a local copy of the GeoJSON stored at
  // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
  script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
  document.getElementsByTagName('head')[0].appendChild(script);
}

// Loop through the results array and place a marker for each
// set of coordinates.
window.eqfeed_callback = function(results) {
  for (var i = 0; i < results.features.length; i++) {
    var coords = results.features[i].geometry.coordinates;
    var latLng = new google.maps.LatLng(coords[1], coords[0]);

    //Creating a marker and putting it on the map
    var marker = new google.maps.Marker({
      position: latLng,
      map: map,
      title: "" + results.features[i].properties.mag,
      mag: results.features[i].properties.mag
    });
    gmarkers.push(marker);
  }
}

// Function to filter markers by category
var filterMarkers = function(category) {
  console.log("category=" + category);
  switch (category) {
    case "4.5=<":
      for (i = 0; i < gmarkers.length; i++) {
        marker = gmarkers[i];
        // If is same category or category not picked
        if (marker.mag <= 4.5) {
          marker.setVisible(true);
        }
        // Categories don't match 
        else {
          marker.setVisible(false);
        }
      }
      break;
    case "4.6 to 4.9":
      for (i = 0; i < gmarkers.length; i++) {
        marker = gmarkers[i];
        // If is same category or category not picked
        if (4.6 <= marker.mag && marker.mag <= 4.5) {
          marker.setVisible(true);
        }
        // Categories don't match 
        else {
          marker.setVisible(false);
        }
      }
      break;
    case ">=5":
      for (i = 0; i < gmarkers.length; i++) {
        marker = gmarkers[i];
        // If is same category or category not picked
        if (5 <= marker.mag) {
          marker.setVisible(true);
        }
        // Categories don't match 
        else {
          marker.setVisible(false);
        }
      }
      break;
    default:
      for (i = 0; i < gmarkers.length; i++) {
        marker = gmarkers[i];
        marker.setVisible(true);
      }
  }
}
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

#map {
  height: 90%;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>

<div class="mapWrap">
  <div id="map-canvas"></div>

  <div class="investCast">

    <select id="mag" onchange="filterMarkers(this.value);">
      <option value="">Selected the magnitude</option>
      <option value="4.5=<">Less than or equal 4.5</option>
      <option value="4.6 to 4.9">Between 4.6 and 4.9</option>
      <option value=">=5">Greater than or equal 5</option>
    </select>

  </div>
</div>

person geocodezip    schedule 21.05.2018

Използвайте filter, за да трансформирате един масив в друг, включително елементи въз основа на условие:

const input = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"mag":5.4,"place":"48km SSE of Pondaguitan, Philippines","time":1348176066,"tz":480,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/usc000csx3","felt":2,"cdi":3.4,"mmi":null,"alert":null,"status":"REVIEWED","tsunami":null,"sig":"449","net":"us","code":"c000csx3","ids":",usc000csx3,","sources":",us,","types":",dyfi,eq-location-map,general-link,geoserve,historical-moment-tensor-map,historical-seismicity-map,nearby-cities,origin,p-wave-travel-times,phase-data,scitech-link,tectonic-summary,"},"geometry":{"type":"Point","coordinates":[126.3832,5.9775,111.16]},"id":"usc000csx3"},{"type":"Feature","properties":{"mag":5.7,"place":"35km ESE of Ndoi Island, Fiji","time":1348175020,"tz":-720,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/usc000csw5","felt":0,"cdi":1,"mmi":2,"alert":"green","status":"REVIEWED","tsunami":null,"sig":"500","net":"us","code":"c000csw5","ids":",usc000csw5,","sources":",us,","types":",dyfi,eq-location-map,geoserve,historical-moment-tensor-map,historical-seismicity-map,losspager,nearby-cities,origin,p-wave-travel-times,phase-data,scitech-link,shakemap,tectonic-summary,"},"geometry":{"type":"Point","coordinates":[-178.3725,-20.753,544.19]},"id":"usc000csw5"},{"type":"Feature","properties":{"mag":3.8,"place":"43km NNE of Talkeetna, Alaska","time":1348174056,"tz":-480,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/ak10562838","felt":0,"cdi":1,"mmi":null,"alert":null,"status":"REVIEWED","tsunami":"1","sig":"222","net":"ak","code":"10562838","ids":",ak10562838,at00mao1rc,","sources":",ak,at,","types":",dyfi,general-link,geoserve,impact-link,nearby-cities,origin,tectonic-summary,"},"geometry":{"type":"Point","coordinates":[-149.8072,62.6916,10.1]},"id":"ak10562838"},{"type":"Feature","properties":{"mag":3.4,"place":"46km ESE of Yunaska Island, Alaska","time":1348171278,"tz":-660,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/ak10562822","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"REVIEWED","tsunami":null,"sig":"178","net":"ak","code":"10562822","ids":",ak10562822,","sources":",ak,","types":",general-link,geoserve,nearby-cities,origin,tectonic-summary,"},"geometry":{"type":"Point","coordinates":[-170.0567,52.4716,127.2]},"id":"ak10562822"},{"type":"Feature","properties":{"mag":4.9,"place":"41km WSW of Kimbe, Papua New Guinea","time":1348163091,"tz":600,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/usc000csng","felt":0,"cdi":1,"mmi":null,"alert":null,"status":"REVIEWED","tsunami":null,"sig":"369","net":"us","code":"c000csng","ids":",usc000csng,","sources":",us,","types":",dyfi,eq-location-map,general-link,geoserve,historical-moment-tensor-map,historical-seismicity-map,nearby-cities,origin,p-wave-travel-times,phase-data,scitech-link,tectonic-summary,"},"geometry":{"type":"Point","coordinates":[149.8211,-5.7346,120.46]},"id":"usc000csng"}]};

const featuresBelowMag5 = input.features.filter(({ properties: { mag } }) => mag < 5);
console.log(featuresBelowMag5);

person CertainPerformance    schedule 20.05.2018
comment
Здравейте, @CertainPerformance, благодаря за отговора. Съжалявам, но аз не съм разработчик, така че не разбрах как да добавя вашия отговор в моя пример. Бихте ли ми показали пълен пример (html, js) в snippet или jsfiddle, моля? Не забравяйте, че моят json се зарежда чрез url. - person Alisson; 21.05.2018
comment
Променливата input съответства на предоставената от вас структура на обекта - просто натиснете Run code snippet и ще видите как филтрира всички тези с по-големи величини. След това можете да предадете филтрирания обект, ако е необходимо. - person CertainPerformance; 21.05.2018