Eric Wiemer
Eric Wiemer

Reputation: 31

Python - Folium Search Plugin Doesn't Search Popup Text in MarkerCluster Group Layer

My folium map, marker cluster, layer control, and search bar all work and show up correctly except for actually using the search bar. The layer I have the search plugin point to when searching is my MarkerCluster layer, which the folium documentation says should be searchable. Anything I type into the search bar it returns "Location not found" which makes me think it's not searching through the MarkerCluster layer correctly, or does not know to search through the text of that layer that is included in the markers' popups.

Here is my code as I have it right now:

import os 
import folium
from folium import plugins
import pandas as pd
from folium.plugins import MarkerCluster
from folium.plugins import Search

#import data including lat/lon, name of service, address of service
df = pd.read_csv('data.csv')

#Create base map zoomed in to Indiana
map=folium.Map(location=[39.80, -86.12],  tiles=None, zoom_start=7)
folium.TileLayer('cartodbpositron', name='COVID-19 Services').add_to(map)

#Make Marker Cluster Group layer
mcg = folium.plugins.MarkerCluster(control=False)
map.add_child(mcg)

#Create layer of markers
#Set marker popups to display name and address of service
for row in df.iterrows():
    row_values=row[1]
    location=[row_values['latitude'], row_values['longitude']]
    popup=popup=(row_values['name']+'<br>'+'<br>'+row_values['address_1']+
                 '<br>'+'<br>'+row_values['city']+','+' '+row_values['state']+
                 '<br>'+row_values['zip'])
    marker=folium.Marker(location=location, popup=popup, min_width=2000)
    marker.add_to(mcg)

#Add search bar
servicesearch = Search(
    layer=mcg,
    geom_type='Point',
    placeholder='Search for a service',
    collapsed=False,
).add_to(map)

#Add layer control
folium.LayerControl().add_to(map)

map

How do I get the search plugin to actually search the test of the marker popups? Then, how do I get the map to highlight or zoom to those searched for markers? Any help is GREATLY appreciated, thank you!

Upvotes: 3

Views: 5455

Answers (3)

user14603676
user14603676

Reputation:

This is my solution:

def visualize_locations_with_marker_cluster(df, zoom=4):
    f = folium.Figure(width=1000, height=500)

    center_lat=34.686567
    center_lon=135.52000

    m = folium.Map([center_lat,center_lon], zoom_start=zoom).add_to(f)
    marker_cluster = MarkerCluster().add_to(m)

    for d in df.iterrows():
        folium.Marker(location=[d[1]["y"], d[1]["x"]], popup=d[1]["company"], name=d[1]["company"]).add_to(marker_cluster)

    servicesearch = Search(
        layer=marker_cluster,
        search_label="name",
        placeholder='Search for a service',
        collapsed=False,
    ).add_to(m)


    return m

First create map, create cluster, loop values in pd.dataframe and create Marekers for Cluster with name label. Next create Search object and add cluster there with search_label="name", label. Finally add it all back to the map

["x", "y"] is longtitude and latitude, company is a search value in my case

Upvotes: 2

I have been struggling a while with the same. I believer this might fix it: add a 'name' or whatever you want to be searched to the marker, e.g.:

marker=folium.Marker(location=location, popup=popup, min_width=2000, name=name)

A little late, but better than never, perhaps.

Upvotes: 0

Pierre-Loic
Pierre-Loic

Reputation: 1564

If you change a little how you add data to the map, it will be easier to use the search bar. You can change the data in your dataframe into a GeoJSON objet. You first need to create a dictionnary for your GeoJSON and use the function folium.GeoJSON() :

geo_json = {
  "type": "FeatureCollection",
  "features": [],
}
for d in df.iterrows():
    temp_dict = {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates":[d[1]["longitude"], d[1]["latitude"]],
        
      },"properties": {"name": d[1]["name"]}
    }
    geo_json["features"].append(temp_dict)
geojson_obj = folium.GeoJson(geo_json).add_to(map)

After that, you just need to change a little your code to add the search bar :

servicesearch = Search(
    layer=geojson_obj,
    search_label="name",
    placeholder='Search for a service',
    collapsed=False,
).add_to(map)

Upvotes: 0

Related Questions