我正在尝试将mapbox集成到静态页面中,但是我很难将Geojson数组馈入MAPBOX,以过程生成标记。我的Ajax调用没有提供错误消息,但是Geojson数据都没有出现在控制台中,并且没有将标记呈现到地图上。当我将一些内联geojson代替我的Geojson时,标记会在地图上生成没有任何问题。关于我在这里错的想法吗?
static_pages_controller.rb
class StaticPagesController < ApplicationController
def map
@experiences = Experience.all
@geojson = Array.new
@experiences.each do |experience|
@geojson << {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [experience.longitude, experience.latitude]
},
properties: {
name: experience.name,
address: experience.location,
:'marker-color' => '#00607d',
:'marker-symbol' => 'circle',
:'marker-size' => 'medium'
}
}
end
respond_to do |format|
format.html
format.json { render json: @geojson } # respond with the created JSON object
end
end
static_pages/map.html.erb
<div id='map' style='width: 100%; height: 750px;'></div>
<script>
$(function() {
mapboxgl.accessToken = 'pk.eyJ1IjoianJvY2tldGxhYiIsImEiOiJTOFhPc1hjIn0.jf1Gd5AeO6xVQoTA_KMhEg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: [-96, 37.8],
zoom: 3
});
map.on('load', function() {
$.ajax({
dataType: 'text',
url: '/map.json',
success: function(data) {
var geojson;
geojson = $.parseJSON(data);
return geojson;
// add markers to map
geojson.features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
},
error:function() {
alert("Could not load the events");
},
});
});
});
</script>
服务器日志
Started GET "/map.json" for 127.0.0.1 at 2018-02-06 16:07:27 -0800
Processing by StaticPagesController#map as JSON
Experience Load (0.3ms) SELECT "experiences".* FROM "experiences"
Completed 200 OK in 3ms (Views: 1.4ms | ActiveRecord: 0.3ms)
我最终弄清楚了!我需要移动一些JavaScript,以便正确喂食Geojson,并等待文档准备就绪并在尝试加载标记和Geojson之前加载地图。
更新了JavaScript
$(function() {
mapboxgl.accessToken = 'pk.eyJ1IjoianJvY2tldGxhYiIsImEiOiJjajZuNnh5dm4wNTgyMndvMXNqY3lydjI4In0.gHVskGK1QuUoxm8sMwugWQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/jrocketlab/cjdaqnwhbb3e52sqwblieddk1',
center: [-96, 37.8],
zoom: 3
});
map.on('load', function() {
$.ajax({
dataType: 'text',
url: '/map.json',
success: function(data) {
var myjson;
myjson = $.parseJSON(data);
var geojson = {
type: 'FeatureCollection',
features: myjson
};
// add markers to map
geojson.features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
},
error:function() {
alert("Could not load the events");
}
});
});
});