当我使用Python folium库将鼠标悬停在世界地图上时,如何显示国家名称和人口?

2024-05-19 09:49:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用folium用python制作了一个网络地图。地图读取包含国家名称和人口编号的population.json文件,并在浏览器上显示地图

代码如下:

import pandas
import folium

map = folium.Map(location=[32, 0], zoom_start=4.3, tiles = "CartoDB positron", max_zoom = 100)


fgp = folium.FeatureGroup(name="Population" )

def colorPicker(population):
    if population < 10000000:
        return 'green'
    elif population >= 10000000 and population < 500000000:
        return 'orange'
    else:
        return 'red'


fgp.add_child(folium.GeoJson(data=open('population.json', 'r', encoding='utf-8-sig').read(), 
style_function=lambda x: {'fillColor': colorPicker(x['properties']['POP2005'])},
tooltip=lambda x: '%s\n%s' % (x['properties']['Name'], x['properties']['POP2005'])

))


map.add_child(fgp)

map.save("index.html")

我创建了feature group(要素组)并添加了_child(子元素),以便根据人口大小为地图上的每个国家添加颜色,代码如下:

style_function=lambda x: {'fillColor': colorPicker(x['properties']['POP2005'])}

我想要的是,每当用户在一个国家上空盘旋时,我都想显示该国家的名称和该国的人口规模。为此,我写道:

tooltip=lambda x: '%s\n%s' % (x['properties']['Name'], x['properties']['POP2005'])

它没有给我国家的名字,而是给了我这个。。。 Picture of map

它应该说“中国:人口规模”,但实际上是“0x24…”

我不知道为什么。我尝试了几种不同的工具提示,例如:

tooltip=lambda x: '{0}\n{1}'.format(x['properties']['Name'], x['properties']['POP2005']) 
tooltip=lambda x: '%s\n%s' % (x['properties']['Name'], x['properties']['POP2005']) 
tooltip= lambda x: {'text': x['properties']['Name']}))
tooltip= lambda x: {'%s': x['properties']['Name']}))

但仍然显示相同的输出

下面是指向population.json文件的链接:file


Tags: lambdanamejsonmapreturn地图properties国家
1条回答
网友
1楼 · 发布于 2024-05-19 09:49:01

使用^{}^{}类:

import folium

m = folium.Map(location=[32, 0],
               zoom_start=4.3,
               tiles = "CartoDB positron",
               max_zoom = 100)

def colorPicker(population):
    if population < 10000000:
        return 'green'
    elif population >= 10000000 and population < 500000000:
        return 'orange'
    else:
        return 'red'

folium.GeoJson(open('population.json', 'r', encoding='utf-8-sig').read(),
               name = 'Population',
               style_function = lambda x: {'fillColor': colorPicker(x['properties']['POP2005'])},
               tooltip = folium.GeoJsonTooltip(fields=('NAME', 'POP2005',),
                                               aliases=('Country','Population')),
               show = True).add_to(m)


#folium.LayerControl().add_to(m)
m

你会得到:

enter image description here

相关问题 更多 >

    热门问题