Tobias G Tobias G - 5 months ago 112
jQuery Question

Filter Google maps markers with input sliders

I am working on a new Wordpress site which my client is going to publish available apartments on. These objects is going to be published with Advanced Custom Fields using the "Map" field. For each new object published, a marker appears on the Google Map on the page.

Now, my problem is, users must be able to filter these markers depending on three things: A minimum number of rooms, minimum area, max rent/price. So to be more specific. If the user sets the minimum number of rooms to 3 in the input slider it is supposed to only show apartments with at least 3 rooms and the same with the other filter options. This is not the problem tho, the user also needs to be able to filter on all the three different options at once. Like this; Minimum number of rooms = 3, Max rent = 1000, Minimum area = 30sq.m. Now it should only show markers on the map that matches the filter values.

This is what I have done so far:

HTML

<div class="range1">
<label></label>
<output for="object-room" class="room-output"></output>
<input type="range" name="object-room" min="1" max="20" step="1" value="1">
</div>

<div class="range2">
<label></label>
<output for="object-size" class="size-output"></output>
<input type="range" name="object-size" min="15" max="300" step="5" value="1">
</div>

<div class="range3">
<label></label>
<output for="object-price" class="price-output"></output>
<input type="range" name="object-price" min="1000" max="20000" step="500" value="4500">
</div>


jQuery

// Filter markers
$marker.each(function(i, obj) {
var objPrice = $(this).data("price");
var objSize = $(this).data("size");
var objRoom = $(this).data("room");

$("[name=object-price]").on("change", function() {
$("[for=object-price]").val(this.value + ' kr');
var priceVal = this.value;

if ( priceVal >= objPrice ) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}

}).trigger("change");

});

Answer

Follow the following step:

  1. Add a array var markers = [] which can be accessible to global. (same usage as your map.markers but try not direct add things to SDK)

  2. In your add_marker() create each marker and push it to markers array. You may use below code to make it easier later.


var marker = new google.maps.Marker(); //with your attribute.
var markerWithData = {'marker': marker, 'price': 123, ...} // all you data belong to that marker.
markers.push(markerWithData );
  1. Add new function filterMarker(): this function get your filter data and loop through markers and set visible at array item's marker attribute.

for(var i=0; i<markers.length; i++){
    //Check markers[i] need to be display or not.
    if(needDisplay){
        markers[i].marker.setVisible(true);
    }else{
        markers[i].marker.setVisible(false);
    }
}

I know this is not clear but i don't know how to descriptive better. If you have any question please comment :)

Comments