Javascript 将传单捆绑在浏览器中使用
我想使用传单加载一个简单的本地网站上的自定义地图 目前我正在使用NodeJS、Express、EJS(作为模板引擎),但我似乎无法使用传单。我也尝试过使用browserify并导入bundle.js脚本,但仍然没有成功 你知道我该怎么做吗Javascript 将传单捆绑在浏览器中使用,javascript,node.js,webpack,browserify,require,Javascript,Node.js,Webpack,Browserify,Require,我想使用传单加载一个简单的本地网站上的自定义地图 目前我正在使用NodeJS、Express、EJS(作为模板引擎),但我似乎无法使用传单。我也尝试过使用browserify并导入bundle.js脚本,但仍然没有成功 你知道我该怎么做吗 //map.js var map=L.map(“地图面板”); var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; var osmAttrib=‘地图数据©贡献者’; var map
//map.js
var map=L.map(“地图面板”);
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib=‘地图数据©贡献者’;
var mapLayer=newl.tillelayer(osmUrl,{minZoom:8,maxZoom:20,attribute:osmAttrib});
addLayer(mapLayer.fitWorld();
//map.setView([location.lat,location.lon],13)代码>
地图
您不能在浏览器中以本机方式使用require()
任何内容,但Browserify或Webpack将允许您将模块捆绑到代码中,以便在浏览器中运行
您应该使用require
语句编写JavaScript代码,然后构建它以生成一个JavaScript包,并使用HTML将其交付给浏览器。每次更改代码时,都需要重新生成,或者向项目中添加一个,并让观察者运行重新生成。重要的是要理解,HTML调用的是bundle.js
,而不是app.js
。您上面发布的代码尚未打包,因此无法使用
此外,您上面发布的代码似乎并没有向地图添加任何可见的内容,除了缩放控件
使用教程代码,我在下面发布了一个工作示例:
目录结构
package.json
app.js
index.html
然后在浏览器中打开index.html
文件,您会看到一张地图。开始的地方是发布您尝试的代码,以及尝试时发生的情况(错误消息和其他输出)。请参阅此链接:谢谢Matt,我原以为没有必要,但现在我添加了它们。我看不到传单.js
正在加载-这将解释L
未定义的原因。非常感谢Matt的详细解释。我试过了,效果很好!现在,我们将尝试将其与express服务器组合在一起!再次感谢你的帮助!令人惊叹的。很高兴它有帮助!
project
node_modules/
app.js
package.json
index.html
dist/
bundle.js
style.css
{
"name": "leaf",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "browserify app.js -o dist/bundle.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"browserify": "^16.2.0"
},
"dependencies": {
"jquery": "^3.3.1",
"leaflet": "^1.3.1"
}
}
// require modules
var L = require('leaflet');
var $ = require('jquery');
// Create the map
var map = L.map('map').setView([41.3921, 2.1705], 13);
// Indicate leaflet the specific location of the images folder that it needs to render the page
L.Icon.Default.imagePath = 'node_modules/leaflet/dist/images/'
// Use OpenStreetMap tiles and attribution
var osmTiles = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var attribution = '© OpenStreetMap contributors';
// Create the basemap and add it to the map
L.tileLayer(osmTiles, {
maxZoom: 18,
attribution: attribution
}).addTo(map);
// Add some geojson from this URL
var geojsonURL = 'http://mappingandco.github.io/geojsonDB/barcelona/neighbourhoods.geojson'
$.getJSON(geojsonURL, function(neighbourhoods) {
L.geoJson(neighbourhoods, {
onEachFeature: function (feature, layer) {
layer.bindPopup(feature.properties.NBarri);
}
}).addTo(map);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Leaflet with browserify template</title>
<link rel="stylesheet" href="node_modules/leaflet/dist/leaflet.css" />
<link rel="stylesheet" href="dist/style.css">
</head>
<body>
<div id="map"></div>
<script src="dist/bundle.js" charset="utf-8"></script>
</body>
</html>
npm install
npm run build