搜尋
首頁後端開發Python教學Python folium的功能怎麼使用

一、效果圖

Python folium的功能怎麼使用

二、圖層控制

在folium官方也提供了一些更明確的方法供我們使用。就比如圖層的控制。官方給予方法名稱是FeatureGroup,導入方式時from folium import FeatureGroup,或folium.FeatureGroup()。具體原理我這裡就不細說了,主要還是看示例:

import folium

def map2png(map_data,out_file='pdf.png'):
	# 1.直接构造,默认底图
	mo = folium.Map(location=[0, 0])
	
    # 2.图层1-高德底图+数据
    fg = folium.FeatureGroup()
    # 2.1 高德地图
    fg.add_child(folium.TileLayer(
        tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
        attr="&copy; <a href=http://ditu.amap.com/>高德地图</a>",
        min_zoom=0,
        max_zoom=19,
        control=True,
        zoom_control=False,
        show=True))
    # 2.2添加一个点
    fg.add_child(folium.Marker(
							location=[45.3311, -121.7113],
							popup="Timberline Lodge",
							icon=folium.Icon(color="green")))
  	#  2.3添加一个线形   
	fg.add_child(folium.PolyLine(
		locations=[[38.68,115.67],
					[38.85,115.48],
					[38.65,115.37],
					[38.68,115.67]],
		color=&#39;green&#39;, weight=2, opacity=1))
 	# 2.4添加一个面
	fg.add_child(folium.Polygon(
	    locations=[[38.68,115.67],
					[38.85,115.48],
					[38.65,115.37],
					[38.68,115.67]], 
		color=&#39;green&#39;, weight=2, 
		fill=True,fill_color = &#39;red&#39;))
	# 2.5将我们的图层加入map
	mo.add_child(fg)
	
	# 3.图层2-重点数据+最上层
	fg2 = folium.FeatureGroup()
	fg2.add_child(folium.Polygon(
	    locations=[[38.68,115.67],
					[38.85,115.48],
					[38.65,115.37],
					[38.68,115.67]], 
		color=&#39;green&#39;, weight=2, 
		fill=True,fill_color = &#39;red&#39;))
	mo.add_child(fg2)
	
	# 4.将图层fg2显示在最上层,keep_in_front的参数必须是FeatureGroup或TileLayer对象
	mo.keep_in_front(fg2)
	
	# 5.根据范围缩放地图
    mo.fit_bounds([[38.68,115.67],
					[38.85,115.48],
					[38.65,115.37],
					[38.68,115.67]])  
					
    root = mo.get_root()
    html = root.render()  # 这个拿到的就是一个html的内容
    # mo.save(&#39;text.html&#39;)

三、指北針

指北針這個功能對於地圖來說不一定是必須的,但是加上總是好的。 FloatImage的使用可以實現該功能,儘管官方文件和原始碼分析中並未提及相關內容。官方文件中提供了許多插件,其中使用最廣泛的是稱為熱力學圖的HeatMap方法。

FloatImage方法實現的是將圖片放到螢幕上,並指定圖片的大小,和螢幕上的位置,參數為整數(FloatImage方法實現了百分比轉換)。我們在二碼的基礎上,將圖片加在了左下角。

fg.add_child(FloatImage(os.path.join(base, &#39;map_png&#39;, &#39;image&#39;, &#39;compass.png&#39;), left=5, bottom=10, width=5))

四、folium添加js和css

folium官方未提供添加js和css的相關方法,網上很多方法應該都是在解讀源碼的基礎上進行的抽取,相對來說比較的單一,沒有針對如何添加js和css進行相關說明。

從原始碼可以知道,folium實現的地圖功能是透過jinjia2實現資料和地圖載入html。

原始碼中主要使用了三種新增資料和地圖的方法。這些方法有缺陷(只能加在最前面),這些方法可以使用大多數場景,如果不涉及對map物件的操作,此三種方法可以滿足要求。

1.header加入js和css

    init_script = """
        var mapsPlaceholder = [];
        L.Map.addInitHook(function () {mapsPlaceholder.push(this);});
    """
    # 加在header最上边
    mo.get_root().header.add_child(folium.Element(init_script))

Python folium的功能怎麼使用

#2.body加入js和css

    init_script = """
        var mapsPlaceholder = [];
        L.Map.addInitHook(function () {mapsPlaceholder.push(this);});
    """
    # 加在body中
    mo.get_root().html.add_child(folium.Element(init_script))

Python folium的功能怎麼使用

#3.script添加js和css

    init_script = """
        var mapsPlaceholder = [];
        L.Map.addInitHook(function () {mapsPlaceholder.push(this);});
    """
    # 加在script中
    mo.get_root().script.add_child(folium.Element(init_script))

Python folium的功能怎麼使用

五、經緯網格線

上一步實現了在html檔案不同位置添加js和css的方法,如果涉及到對map物件的操作,可能存在不滿足的情況,例如添加經緯網格線。實現經緯網格線這個功能比較麻煩,主要存在以下困難:

1.官方沒有相關的方法和插件(目前沒有);

2.folium是依賴leadlet.js實現的第三方函式庫,想實現經緯線需要熟悉leaflet(在網上只找到一篇相關文章);

#3.上邊的文章是前端完成,沒有直接後端實現的方法。

4.前端實作的方法是直接建構的地圖,我們這裡是地圖創建物件不可取得(地圖物件隨機產生)。

如何才能事項經緯網格線呢?

我們需要將物件儲存在建立map物件時,然後取得map物件並根據縮放層​​級實作網格線。一個重要的任務是確保在創建map物件之前和之後將javascript程式碼正確地嵌入到html頁面中。

其中map物件建立時將物件儲存在四中已經實現,透過學習folium源碼,重寫了添加js的方法實現map物件建立後添加js。

Python folium的功能怎麼使用

1.html頁面實作經緯度網格

Python folium的功能怎麼使用

#
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 
    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" rel="external nofollow" 
    />
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
 
    <title>leaflet-经纬网格</title>
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
      }
      .leaflet-div-icon {
        background: none;
        border: none;
      }
    </style>
  </head>
 
  <body>
    <div id="map" ></div>
 
    <script>
      let map = L.map("map", { renderer: L.canvas({ padding: 0.5 }) }).setView(
        [25.127879288597576, 118.37905883789064],
        4
      );
      // 添加背景图层
      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        attribution:
          &#39;&copy; <a href="https://www.openstreetmap.org/copyright" rel="external nofollow" >OpenStreetMap</a> contributors&#39;,
      }).addTo(map);
 
      // 创建图层
      let lonLatGridLineLayer = L.featureGroup().addTo(map);
      // 经纬网格生成方法
      let addLonLatLine = () => {
        let zoom = map.getZoom();
        let bounds = map.getBounds();
        let north = bounds.getNorth();
        let east = bounds.getEast();
        // 经纬度间隔
        let d = 90 / Math.pow(2, zoom - 1);
        // 经线网格
        for (let index = -180; index <= 360; index += d) {
          // 判断当前视野内
          if (bounds.contains([north, index])) {
            // 绘制经线
            let lonLine = L.polyline(
              [
                [-90, index],
                [90, index],
              ],
              { weight: 1, color: "blue" }
            );
            lonLatGridLineLayer.addLayer(lonLine);
            // 标注
            let text = index.toFixed(1) + "°";
            // 动态计算小数位数
            if (zoom > 10) {
              text = index.toFixed((zoom - 8) / 2) + "°";
            }
            let divIcon = L.divIcon({
              html: `<div >${text}</div>`,
              iconAnchor: [0, -5],
            });
            let textMarker = L.marker([north, index], { icon: divIcon });
            lonLatGridLineLayer.addLayer(textMarker);
          }
        }
		if(d>90)d=90;
        // 纬线网格
        for (let index = -90; index <= 90; index += d) {
          if (bounds.contains([index, east])) {
            let lonLine = L.polyline(
              [
                [index, -180],
                [index, 360],
              ],
              { weight: 1, color: "blue" }
            );
            lonLatGridLineLayer.addLayer(lonLine);
            // 标注
            let text = index.toFixed(1) + "°";
            if (zoom > 10) {
              text = index.toFixed((zoom - 8) / 2) + "°";
            }
            let divIcon = L.divIcon({
              html: `<div >${text}</div>`,
              iconAnchor: [(text.length + 1) * 6, 0],
            });
            let textMarker = L.marker([index, east], { icon: divIcon });
            lonLatGridLineLayer.addLayer(textMarker);
          }
        }
      };
      addLonLatLine();
      map.on("zoomend move", () => {
        lonLatGridLineLayer.clearLayers();
        addLonLatLine();
      });
    </script>
  </body>
</html>

2.自訂網格線的類別

透過原始碼的類別繼承關係,我採取繼承MacroElement類別。

from branca.element import MacroElement,
from jinja2 import Template
from folium.vector_layers import path_options

class Jwwg(MacroElement):
    """自定义经纬线网格"""
    _template = Template("""
        {% macro script(this, kwargs) %}
                    var map = mapsPlaceholder.pop();
                    // 创建图层
                    let lonLatGridLineLayer = L.featureGroup().addTo(map);
                    // 经纬网格生成方法
                    let addLonLatLine = () => {
                        let zoom = map.getZoom();
                        let bounds = map.getBounds();
                        let north = bounds.getNorth();
                        let east = bounds.getEast();
                        // 经纬度间隔
                        let d = 90 / Math.pow(2, zoom - 1);
                        // 经线网格
                        for (let index = -180; index <= 360; index += d) {
                            // 判断当前视野内
                            if (bounds.contains([north, index])) {
                                // 绘制经线
                                let lonLine = L.polyline(
                                    [
                                        [-90, index],
                                        [90, index],
                                    ],
                                    {weight: 1, color: "blue"}
                                );
                                lonLatGridLineLayer.addLayer(lonLine);
                                // 标注
                                let text = index.toFixed(1) + "°";
                                // 动态计算小数位数
                                if (zoom > 10) {
                                    text = index.toFixed((zoom - 8) / 2) + "°";
                                }
                                let divIcon = L.divIcon({
                                    html: `<div >${text}</div>`,
                                    iconAnchor: [0, -5],
                                });
                                let textMarker = L.marker([north, index], {icon: divIcon});
                                lonLatGridLineLayer.addLayer(textMarker);
                            }
                        }
                        if (d > 90) d = 90;
                        // 纬线网格
                        for (let index = -90; index <= 90; index += d) {
                            if (bounds.contains([index, east])) {
                                let lonLine = L.polyline(
                                    [
                                        [index, -180],
                                        [index, 360],
                                    ],
                                    {weight: 1, color: "blue"}
                                );
                                lonLatGridLineLayer.addLayer(lonLine);
                                // 标注
                                let text = index.toFixed(1) + "°";
                                if (zoom > 10) {
                                    text = index.toFixed((zoom - 8) / 2) + "°";
                                }
                                let divIcon = L.divIcon({
                                    html: `<div >${text}</div>`,
                                    iconAnchor: [(text.length + 1) * 6, 0],
                                });
                                let textMarker = L.marker([index, east], {icon: divIcon});
                                lonLatGridLineLayer.addLayer(textMarker);
                            }
                        }
                    };
                    addLonLatLine();
                    map.on("zoomend move", () => {
                        lonLatGridLineLayer.clearLayers();
                        addLonLatLine();
                    });
                   {% endmacro %}
                """)

    def __init__(self, **kwargs):
        super(Jwwg, self).__init__()
        self._name = &#39;Jwwg&#39;
        self.options = path_options(line=True, **kwargs)

3.實作網格線

import folium

def map2png(map_data,out_file=&#39;pdf.png&#39;):
	# 1.直接构造,默认底图
	mo = folium.Map(location=[0, 0])
	
    # 2.图层1-高德底图+数据
    fg = folium.FeatureGroup()
    # 2.1 高德地图
    fg.add_child(folium.TileLayer(
        tiles=&#39;http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}&#39;,
        attr="&copy; <a href=http://ditu.amap.com/>高德地图</a>",
        min_zoom=0,
        max_zoom=19,
        control=True,
        zoom_control=False,
        show=True))
    # 2.2添加一个点
    fg.add_child(folium.Marker(
							location=[45.3311, -121.7113],
							popup="Timberline Lodge",
							icon=folium.Icon(color="green")))
  	#  2.3添加一个线形   
	fg.add_child(folium.PolyLine(
		locations=[[38.68,115.67],
					[38.85,115.48],
					[38.65,115.37],
					[38.68,115.67]],
		color=&#39;green&#39;, weight=2, opacity=1))
 	# 2.4添加一个面
	fg.add_child(folium.Polygon(
	    locations=[[38.68,115.67],
					[38.85,115.48],
					[38.65,115.37],
					[38.68,115.67]], 
		color=&#39;green&#39;, weight=2, 
		fill=True,fill_color = &#39;red&#39;))
	# 2.5将我们的图层加入map
	mo.add_child(fg)
	# 5.根据范围缩放地图
    mo.fit_bounds([[38.68,115.67],
					[38.85,115.48],
					[38.65,115.37],
					[38.68,115.67]])  
    # 网格线
    init_script = """
        var mapsPlaceholder = [];
        L.Map.addInitHook(function () {mapsPlaceholder.push(this);});
    """			
    mo.get_root().script.add_child(folium.Element(init_script))
   	Jwwg().add_to(mo)
   	
    root = mo.get_root()
    html = root.render()  # 这个拿到的就是一个html的内容
    # mo.save(&#39;text.html&#39;)

以上是Python folium的功能怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
2小時的Python計劃:一種現實的方法2小時的Python計劃:一種現實的方法Apr 11, 2025 am 12:04 AM

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python:探索其主要應用程序Python:探索其主要應用程序Apr 10, 2025 am 09:41 AM

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

您可以在2小時內學到多少python?您可以在2小時內學到多少python?Apr 09, 2025 pm 04:33 PM

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎?如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎?Apr 02, 2025 am 07:18 AM

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到?如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python 3.6加載Pickle文件報錯"__builtin__"模塊未找到怎麼辦?Python 3.6加載Pickle文件報錯"__builtin__"模塊未找到怎麼辦?Apr 02, 2025 am 07:12 AM

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

如何提高jieba分詞在景區評論分析中的準確性?如何提高jieba分詞在景區評論分析中的準確性?Apr 02, 2025 am 07:09 AM

如何解決jieba分詞在景區評論分析中的問題?當我們在進行景區評論分析時,往往會使用jieba分詞工具來處理文�...

如何使用正則表達式匹配到第一個閉合標籤就停止?如何使用正則表達式匹配到第一個閉合標籤就停止?Apr 02, 2025 am 07:06 AM

如何使用正則表達式匹配到第一個閉合標籤就停止?在處理HTML或其他標記語言時,常常需要使用正則表達式來�...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境