Mapbox GL JS學習筆記二:Nginx搭建本地靜態資源伺服器
聲明:我本地開發使用的Mac系統,所以不敢保證在其它系統尤其是Windows系統下可行。
1.Mac下安裝Nginx,最簡單的方式使用homebrew安裝。可能有些人電腦上沒有homebrew,首先先安裝homebrew。
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)";
查看homebrew安裝列表可以使用命令
brew list
然後就是使用homebrew安裝nginx
brew install nginx
啟動nginx:

2.查看Nginx配置路徑
nginx -t
輸出配置路徑
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is oknginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
3.查看Nginx的配置內容
cat /usr/local/etc/nginx/nginx.conf
顯示默認配置內容
#user nobody;worker_processes 1;#error_log logs/error.log;#error_log logs/error.log notice;#error_log logs/error.log info;#pid logs/nginx.pid;events { worker_connections 1024;}http { include mime.types; default_type application/octet-stream; #log_format main $remote_addr - $remote_user [$time_local] "$request" # $status $body_bytes_sent "$http_referer" # "$http_user_agent" "$http_x_forwarded_for"; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 8080; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ .php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ .php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apaches document root # concurs with nginxs one # #location ~ /.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #} include servers/*;}
4.要配置Nginx作為靜態資源服務需要進行如下配置,
比如假設我的靜態資源伺服器本地路徑是
/Users/lsw/Destop/GIS/mapbox_static_server
第一步,首先需要修改默認配置 nginx.conf 增加如下配置內容
// 存放矢量瓦片內容location /tiles/ { root /Users/lsw/Desktop/GIS/mapbox_static_server/;}
如果需要訪問文件夾,則增加配置 autoindex參數on(可以訪問文件夾),off(禁止訪問文件夾)。默認是off禁止訪問文件夾,主要是考慮到安全的問題。
// 存放矢量瓦片內容location /tiles/ { root /Users/lsw/Desktop/GIS/mapbox_static_server/; autoindex on;}
第二步是需要考慮跨域的問題,這個是做前端不需要解決的問題,Nginx配置解決跨域問題還是非常簡單的,只需要在配置中加入可以訪問的域名就可以了,這裡我才用直接容許所有訪問,所以跨域問題解決方案配置如下:
location /tiles/ { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Credentials true; add_header Access-Control-Allow-Methods GET, POST, OPTIONS; add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type; root /Users/lsw/Desktop/GIS/mapbox_static_server/;}
修改完成的完整配置如下:
#user nobody;worker_processes 1;#error_log logs/error.log;#error_log logs/error.log notice;#error_log logs/error.log info;#pid logs/nginx.pid;events { worker_connections 1024;}http { include mime.types; default_type application/octet-stream; #log_format main $remote_addr - $remote_user [$time_local] "$request" # $status $body_bytes_sent "$http_referer" # "$http_user_agent" "$http_x_forwarded_for"; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { # 修改默認的監聽埠 8080 為 7777 listen 7777; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } # 靜態資源目錄 location /tiles/ { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Credentials true; add_header Access-Control-Allow-Methods GET, POST, OPTIONS; add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type; # 靜態資源根目錄 root /Users/lsw/Desktop/GIS/mapbox_static_server/; autoindex on; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ .php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ .php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apaches document root # concurs with nginxs one # #location ~ /.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #} include servers/*;}
第三步修改完成配置後保存,重新載入nginx。
//nginx啟動、停止、重啟相關命令//啟動nginx//停止nginx -s stop//重新載入nginx -s reload
第四步,將通過mb-util工具導出的mbtile文件瓦片放置在靜態資源目錄中,然後就可以在前端訪問相關資源。

第五步,前端代碼如下:
<!DOCTYPE html><html><head> <meta charset=utf-8 /> <title>Display a map</title> <meta name=viewport content=initial-scale=1,maximum-scale=1,user-scalable=no /> <script src=https://api.tiles.mapbox.com/mapbox-gl-js/v0.41.0/mapbox-gl.js></script>;; <link href=https://api.tiles.mapbox.com/mapbox-gl-js/v0.41.0/mapbox-gl.css; rel=stylesheet /> <style> body { margin:0; padding:0; } #map { position:absolute; top:0; bottom:0; width:100%; } </style></head><body><div id=map></div><script> //使用註冊Mapbox時候後台自動生成的token mapboxgl.accessToken = pk.eyJ1Ijoic2hpd2VpaGFwcHkiLCJhIjoiY2oxb2xleW9hMDE4NzJ3bWh1MDc5bzk4MyJ9.YEJquEqdZcW5W2vpT3Wl9w; var map = new mapboxgl.Map({ container: map, // 放置的div的id style: mapbox://styles/mapbox/streets-v9, // mapbox後台生成的style樣式 center: [107.88, 24.57],// 地圖顯示中心點位置 zoom: 7,// 開始的縮放級別 maxZoom: 16 }); map.on(load, function() { //訪問本地的伺服器,需要注意的是這個路徑中多了一個hechi4326,這是我本地存放瓦片的文件夾 var city_tile_source = { type: vector, tiles: [ http://localhost:7777/tiles/hechi4326/{z}/{x}/{y}.pbf ], maxzoom: 16 }; var city_polygon_layer = { id: city_polygon_id, type: fill, source: city_tile_source, source-layer: hechi, paint: { "fill-color": "#00ffff", "fill-opacity": 0, "fill-outline-color": "#ff0000" } }; var city_normal_line_layer = { id: city_normal_line_id, type: line, source: city_tile_source, source-layer: hechi, layout: { line-join: round, line-cap: round }, paint: { "line-color": "#0000ff", "line-width": 2 } }; var city_select_line_layer = { id: city_select_line_id, type: line, source: city_tile_source, source-layer: hechi, layout: { line-join: round, line-cap: round }, paint: { "line-color": "#ff0000", "line-width": 2 }, "filter": ["==", "OBJECTID", ""] }; map.addSource(city_tile_source, city_tile_source); map.addLayer(city_polygon_layer); map.addLayer(city_normal_line_layer); map.addLayer(city_select_line_layer); }); map.on(click, function(e) { map.setFilter("city_select_line_id", ["==", "OBJECTID", ""]) var features = map.queryRenderedFeatures(e.point, { layers: [city_polygon_id] }); if (!features.length) { return; } var feature = features[0]; for (var key in feature.properties) { console.log("key is: " + key + ", value is: " + feature.properties[key]) } map.setFilter("city_select_line_id", ["==", "OBJECTID", feature.properties.OBJECTID]) var popup = new mapboxgl.Popup() .setLngLat(e.lngLat) .setHTML("<p>"+ feature.properties.QH_NAME+"</p>") .addTo(map); });</script></body></html>
顯示結果:

點擊操作後顯示結果:

這樣一個本地的靜態資源伺服器就搭建完成。其實在這個操作過程中我們又引入了新的問題,
- 瓦片文件mbtile如何生成?
- mb-util是什麼工具?
- 如何不同通過token來訪問API?
等等,這些問題我們將在接下來的內容一一解答。
推薦閱讀:
