How to display markers at specific zoom levels?

Viewed 406

I was able to display a marker for each part of geography for the USA data (using US data as an example since can't display the work data results) using below:

import dload
from shapely.geometry import shape
import geopandas as gpd
import pandas as pd
import folium

json_string = 'https://raw.githubusercontent.com/datasets/geo-admin1-us/master/data/admin1-us.geojson'

j = dload.json(json_string)

gdf_usa = gpd.GeoDataFrame.from_features(j["features"])
gdf_usa.head()

gdf_usa_new = gpd.GeoDataFrame(gdf_usa, crs="EPSG:4326", geometry='geometry')

usa_map = gdf_usa_new.explore(tiles='CartoDB  positron')
usa_map

gdf_usa_new["long"] = gdf_usa_new.to_crs(epsg='4326').centroid.map(lambda p: p.x)
gdf_usa_new["lat"] = gdf_usa_new.to_crs(epsg='4326').centroid.map(lambda p: p.y)

for i in range(0,len(gdf_usa_new)):
    folium.Marker(
      location=[gdf_usa_new.iloc[i]['lat'], gdf_usa_new.iloc[i]['long']],
      popup=gdf_usa_new.iloc[i]['name'],
      icon=folium.DivIcon(html=f"""<div style="font-family: courier new; color: white">{gdf_usa_new.iloc[i]['name']}</div>""")
   ).add_to(usa_map)

usa_map

Given the above, I get the result below. As can be seen, the markers are too close to each other and thus overlap in the Eastern part of the USA.

enter image description here

When I zoom in, the markers appear to be clearer and thus don't overlap.

enter image description here

Therefore, how can I modify the code so that the markers appear as I zoom in into the map? Therefore, when map is zoomed out, only certain markers appear and when I zoom in the rest appear.

I tried to follow the answer below, but have hard time understanding where to include the suggested answer in the above code:

https://gis.stackexchange.com/questions/216558/leaflet-resize-markers-in-layer-when-zoom-in

Update, I have added the code from the above link (see below) but the results of the map still stay the same.

usa_map.get_root().html.add_child(folium.Element("""
var ar_icon_1 = ...;
var ar_icon_2 = ...;
var ar_icon_1_double_size = ...;
var ar_icon_2_double_size = ...;


map.on('zoomend', function() {
    var currentZoom = map.getZoom();
    if (currentZoom > 5) {
        all_testptLayer.eachLayer(function(layer) {
            if (layer.feature.properties.num < 0.5)
                return layer.setIcon(ar_icon_1);
            else if (feature.properties.num < 1.0)
                return layer.setIcon(ar_icon_2);
        });
    } else {
        all_testptLayer.eachLayer(function(layer) {
            if (layer.feature.properties.num < 0.5)
                return layer.setIcon(ar_icon_1_double_size);
            else if (feature.properties.num < 1.0)
                return layer.setIcon(ar_icon_2_double_size);
        });
    }
});
""")).add_to(usa_map)

Thanks

EDIT: I know that certain tiles display the state names for the USA. However, for my line of work, I am working with the Electoral Districts of Ontario. The tiles do not display them. Therefore, I am using the for loop above to display the Electoral District names for each Electoral District in Ontario.

1 Answers

Alright, since none of you know, here is what you do.

  1. Open the HTML file of the map in Notepad++.
  2. For the area of interest, find map_... and u003e... where ... is the State Name or the Electoral District ID. E.g. u003eArizona.
  3. Take note of the marker_... and div_icon_...
  4. Right before the at the bottom of the notepad, insert the following for each of the area of interest:
        var myIcon = L.divIcon({className: 'my-div-icon'});

            map_....on('zoomend', function() {  
            var currZoom = map_....getZoom();
            prevZoom = currZoom;                     
                    if (map_....getZoom() <9){                      
            marker_....setIcon(myIcon);
                    }
                    else {                        
            marker_....setIcon(div_icon_...);

                    }
                }
            );
  1. Save
  2. Refresh the opened HTML file or open the HTML file. 6.5 Note, if you are going to run python code and create a new map every time, then the above values need also be updated in the code.
  3. Profit.
Related