I'm trying to set up a slightly altered version of Patrick Wied's heatmap.js demo w/ leaflet in this jsfiddle, but can't get the heatmap layer to render.
Any idea what's going on? Code below
Thanks in advance for any assistance.
Josh
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js"></script>
<script src="https://unpkg.com/heatmap.js#2.0.5"></script>
<script src="https://unpkg.com/leaflet-heatmap#1.0.0"></script>
<div class="map-container">
<div id="map-here" style="width: 100%; height: 500px"></div>
</div>
<div class="heatmap" id="map-canvas">
</div>
<div class="map-controls">
JAVASCRIPT:
var map = L.map('map-here').setView([37.7829, -122.1312], 10);
var baseLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '[[Attribution]]',
id: 'mapbox.streets'
}).addTo(map);
var refs = new L.LayerGroup()
refs.addTo(map)
map.refs = refs
var cfg = {
"radius": 2,
"maxOpacity": .8,
"scaleRadius": true,
"useLocalExtrema": true,
latField: 'lat',
lngField: 'lng',
valueField: 'count'
};
var heatmapLayer = new HeatmapOverlay(cfg);
var testData = {
max: 8,
data: [{
lat: 37.7829,
lng: -122.1312,
count: 3
}, {
lat: 37.7829,
lng: -122.1312,
count: 1
}, {
lat: 37.7821,
lng: -122.1312,
count: 1
}, {
lat: 37.783,
lng: -122.1312,
count: 1
}]
};
var map = new L.Map('map-canvas', {
center: new L.LatLng(37.7829, -122.1312),
zoom: 4,
layers: [refs, heatmapLayer]
});
heatmapLayer.setData(testData);
The problem is that you are trying to create two Leaflet maps in two divs (map-here and map-canvas) instead of adding overlays to one single map.
You only need to create one map with as many layers as you want.
//You don't need that map - commeted out
//var map = L.map('map-here').setView([37.7829,-122.1312], 10);
var baseLayer = L.tileLayer( 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '[[Attribution]]',
id: 'mapbox.streets'
}
)
//.addTo(map);
var refs = new L.LayerGroup()
//refs.addTo(map)
//map.refs = refs
var cfg = {
"radius": 2,
"maxOpacity": .8,
"scaleRadius": true,
"useLocalExtrema": true,
latField: 'lat',
lngField: 'lng',
valueField: 'count'
};
var heatmapLayer = new HeatmapOverlay(cfg);
var testData = {
max: 8,
data: [{lat:37.7829,lng:-122.1312,count:3},{lat:37.7829,lng:-122.1312,count:1},{lat:37.7821,lng:-122.1312,count:1},{lat:37.783,lng:-122.1312,count:1}]
};
var map = new L.Map('map-here', {
center: new L.LatLng(37.7829,-122.1312),
zoom: 6,
layers: [baseLayer,refs, heatmapLayer]
});
heatmapLayer.setData(testData);
Please look at this fiddle for the visual: https://jsfiddle.net/vaillant/un1rogw2/
Also, what was the role of the refs layer? This layer seems to be empty. And you might want to change the options of your heatmap layer.
When you alter version of tutorials, it would be great to explain what you were hoping to achieve that was not in the initial tutorial.
Related
i can display json lat and lon in map but i want draw lines between two selected points.
like this Here
here i can click all place in Map but i want enable click only displayed points only.
i used this link to display my points Link2 now i want draw lines between two points
<script>
var flickrSource = new ol.source.Vector();
function flickrStyle(feature) {
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: 'white',
width: 2
}),
fill: new ol.style.Fill({
color: 'green'
}),
}),
text: new ol.style.Text({
text: feature.getGeometryName(),
fill: new ol.style.Fill({color: 'blue'}),
stroke: new ol.style.Stroke({color: 'white', width: 1}),
offsetX: 0,
offsetY: 15
}),
});
return [style];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([-1.812, 52.443], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 3
});
var source = new ol.source.Vector({wrapX: false});
var map = new ol.Map({
target: 'map',
layers: [layer, flickrLayer],
view: view
});
function successHandler(data) {
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
data.items.forEach(function(item) {
var feature = new ol.Feature(item);
feature.setGeometryName(item.name);
var coordinate = transform([parseFloat(item.longitude), parseFloat(item.latitude)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
flickrSource.addFeature(feature);
});
}
</script>
Get the co-ordinates of this two points and draw LineString
var thing = new ol.geom.LineString(points);
var featurething = new ol.Feature({
name: "Thing",
geometry: thing
});
flickrSource.addFeature(featurething);
var flickrSource = new ol.source.Vector();
var data = {
"items": [{
name: 'geo1',
longitude: "0.0",
latitude: "0.0"
}, {
name: 'geo1',
longitude: "5.0",
latitude: "5.0"
}]
};
function flickrStyle(feature) {
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: 'white',
width: 2
}),
fill: new ol.style.Fill({
color: 'green'
}),
}),
text: new ol.style.Text({
text: feature.getGeometryName(),
fill: new ol.style.Fill({
color: 'blue'
}),
stroke: new ol.style.Stroke({
color: 'white',
width: 1
}),
offsetX: 0,
offsetY: 15
}),
});
return [style];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource
//style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0.0, 0.0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 5
});
var source = new ol.source.Vector({
wrapX: false
});
var map = new ol.Map({
target: 'map',
layers: [layer, flickrLayer],
view: view
});
function successHandler(data) {
var points = [];
data.items.forEach(function(item) {
var point = ol.proj.transform([parseFloat(item.longitude), parseFloat(item.latitude)], 'EPSG:4326', 'EPSG:3857');
points.push(point);
var geometry = new ol.geom.Point(point);
var feature = new ol.Feature({
name: item.name,
geometry: geometry
});
flickrSource.addFeature(feature);
var thing = new ol.geom.LineString(points);
var featurething = new ol.Feature({
name: "Thing",
geometry: thing
});
flickrSource.addFeature(featurething);
});
}
successHandler(data);
<link href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.js"></script>
<div id="map"></div>
Here is the code...
Here is the vector source, layers and map:
// Vector source of data points
var flickrSource = new ol.source.Vector();
// Style function for the data points
function flickrStyle(feature) {
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: 'white',
width: 2
}),
fill: new ol.style.Fill({
color: 'green'
})
}),
text: new ol.style.Text({
text: feature.getGeometryName(),
fill: new ol.style.Fill({color: 'blue'}),
stroke: new ol.style.Stroke({color: 'white', width: 1}),
offsetX: 0,
offsetY: 15
})
});
return [style];
}
// Layers
var osmLayer = new ol.layer.Tile({ source: new ol.source.OSM() });
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
// MAP
var map = new ol.Map({
target: 'map',
layers: [osmLayer, flickrLayer],
view: new ol.View({
center: ol.proj.transform([0, 20], 'EPSG:4326', 'EPSG:3857'),
zoom: 3
})
});
Then here is the data points and placing them on the map:
// Data points
var data = {
"items": [{
name: 'p1',
longitude: "0.0",
latitude: "0.0"
}, {
name: 'p2',
longitude: "50.0",
latitude: "50.0"
}, {
name: 'p3',
longitude: "50.0",
latitude: "-50.0"
}]
};
// Placing data points on the map
function placePoints(data) {
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
data.items.forEach( function(item) {
// for each item of data points we create feature geometry
// with coords contained in data and add them to the source
var feature = new ol.Feature(item);
feature.setGeometryName(item.name);
var coordinate = transform(
[parseFloat(item.longitude), parseFloat(item.latitude)]
);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
flickrSource.addFeature(feature);
} );
}
placePoints(data); // do the stuff of placing points
And then the interaction for drawing the lines between points:
// select interaction working on "click"
var mySelectInteraction = new ol.interaction.Select({
condition: ol.events.condition.click,
multi: false
});
// init coords of line to draw between points
var pointA = null;
var pointB = null;
// Interaction on points for drawing lines between
mySelectInteraction.on('select', function(e) {
if (e.selected.length === 0) {
// clicking nothing, so reset points coords
pointA = null;
pointB = null;
}
else {
// Feature clicked and its coords
var feature = e.target.getFeatures().item(0);
var coords = feature.getGeometry().getCoordinates();
// Definition of coords points
if (pointA === null) { pointA = coords; }
else { pointB = coords; }
if ( pointA !== null && pointB !== null) {
var LinesSource = new ol.source.Vector();
var LinesLayer = new ol.layer.Vector({ source : LinesSource });
map.addLayer( LinesLayer );
// Line construction
LinesSource.addFeature( new ol.Feature({
geometry : new ol.geom.LineString( [pointA, pointB] )
}) );
// Reset points for next drawing
pointA = null;
pointB = null;
}
}
});
map.addInteraction(mySelectInteraction);
Works great for me!
I am new to gmaps4 and i have tried a lot but i was not able to find how to create a geodesic map, if i have single source and multiple destination using gmap4 rails.
So far i have tried this
Js
var locations = [
//Starting Point is "Home", and links to other locations"//
['Home', 37.774930, -122.419416],
['Location-1', 35.689487, 139.691706],
['Location-2', 48.856614, 2.352222],
['Location-3', -33.867487, 151.206990]
]
function initMap() {
var myLatLng = {
lat: 12.363,
lng: -131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: {
lat: 0,
lng: 0
}
});
var markers = [];
var bounds = new google.maps.LatLngBounds();
// Add the markers and infowindows to the map
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
title: locations[i][0],
map: map
})
markers.push(marker);
bounds.extend(marker.getPosition());
if (i > 0) {
var sitepath = new google.maps.Polyline({
path: [markers[0].getPosition(), marker.getPosition()],
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
}
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initMap);
Html
<div id="map"></div>
but i am not able to understand how to do it using gmaps4 rails
I'm trying to create a Google Map that will draw out a race course from a list of lat & lng in my MVC model. I have successfully done this with markers but I need to do it with polylines to create a path of the course. Below is what I have but can't get the lines to show up.
Any suggestions?
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=false"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(#Model.Courses.Latitude, #Model.Courses.Longitude),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
#foreach (var item in Model.CourseRatings.ValuesList)
{
<text>addMarker(#item.Item2, #item.Item3)</text>
}
var flightPath = new google.maps.Polyline({
path: function addMarker(x, y) { new google.maps.LatLng(x, y); },
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Thank you!
For the path in your flightPath Polyline, supply it with an array of your points, rather than a reference to a function. Which should looks something like this:
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
Also consider using the snap to road api to smoother your polyline.
This worked for me but I'm going to try the smoothing you mentioned:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=false"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(#Model.Courses.Latitude, #Model.Courses.Longitude),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var flightPathCoordinates =
[
#foreach (var item in Model.CourseRatings.ValuesList)
{
<text>new google.maps.LatLng(#item.Item2, #item.Item3),</text>
}
];
var flightPath = new google.maps.Polyline({
path: flightPathCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
in my ror app(ruby on rails),one of page google.js.erb function show google map, i add add position function,i use extjs frame,however i encounter some stronger problem, relative code is below
Ext.onReady(function () {
var mapOptions =
{
zoom: 6,
center: new google.maps.LatLng(30.26, 120.19),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
mapTypeControl: true
};
var map = new google.maps.Map(Ext.getDom('mapDiv'), mapOptions);
var googlemappanel=Ext.create('Ext.panel.Panel', {
items: [
{
xtype: 'panel',
region: 'east',
items: [
Ext.create('Ext.form.Panel', {
id: 'zone-form',
items: [
{xtype:"textfield",fieldLabel: '<%= t('code') %>',name: "code", id: 'zoneid'}
],
buttons: [{
handler: function(){
Ext.getCmp('zone-form').getForm().submit({
url : 'basestation_edit',
success : function(form, action){
var base=action.result.griddata
for(var i=0; i<action.result.griddata.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(base[i].latitude,base[i].longitude),
map: map
});
google.maps.event.addListener(marker, "click", function(event) {
Ext.getCmp('zoneid').setValue(base[i].id);
})
}
}
....
when i submit the form,google marker is added to the map. however when i click the marker, firebug throw out TypeError: base[i] is undefined error, google marker is added normal, it seems variable i is recovery,set global i don't solve the problem。
any help!
I'm not a developer and i'm trying to learn javascript step by step. Now, I need to add a simple infobox in the gmaps that I'm working on. The problem is that, I add the code as explained in the google reference but it doesn't work: in the beginning i was using infowindow wich worked well but wasn't so customized. I also put the infobox.js link in that page and it is the last release.
This is test page: http://www.squassabia.com/aree_espositive_prova2.asp
What i need to do is to display the message you see in the code (boxText.innerHTML), just to understand it step by step and to keep things simple. After that I'm going to style it and add data from xml (which I think is not going to be that difficult).
As i didn't fint any solution in any of the old posts, if anyone of you can give me a clue on how to solve the problem, would be very appreciated, I've tried everything and put infobox stuff pretty much everywhere :(
Cheers
I give you the initialize() code:
//icone custom
var customIcons = {
negozio: {icon: '/images/gmaps/mc.png'},
outlet: {icon: '/images/gmaps/pin_fuc_outlet.png'},
sede: {icon: '/images/gmaps/pin_fuc_home.png'}
};
var clusterStyles = [
{
textColor: 'white',
url: '/images/gmaps/mc.png',
height: 48,
width: 48
}];
function initialize() {
//creo una istanza della mappa
var map = new google.maps.Map(document.getElementById("mapp"), {
center: new google.maps.LatLng(45.405, 9.867),
zoom: 9,
mapTypeId: 'roadmap',
saturation: 20, //scrollwheel: false
});
//stile della mappa
var pinkroad = [ //creo un array di proprietà
{
featureType: "all", //seleziono la feature
stylers: [{gamma: 0.8 },{ lightness: 50 },{ saturation: -100}]
},
{
featureType: "road.highway.controlled_access",
stylers: [{ hue: "#FF3366" },{ saturation: 50 },{ lightness: -5 }]
}
];
map.setOptions({styles: pinkroad});
var name;
//Creates content and style
var boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
boxText.innerHTML = "Prova Infobox<br >Successo!!Test Text";
var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-140, 0)
,zIndex: null
,boxStyle: {background: "url('tipbox.gif') no-repeat", opacity: 0.75, width: "280px"}
,closeBoxMargin: "10px 2px 2px 2px"
,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
};
var ib = new InfoBox(myOptions);
//creo il marker
downloadUrl("xml/negozi.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
var type = markers[i].getAttribute("tipo");
var address = markers[i].getElementsByTagName("indirizzo")[0].childNodes[0].nodeValue;
var city = markers[i].getElementsByTagName("citta")[0].childNodes[0].nodeValue;
var phone = markers[i].getElementsByTagName("telefono")[0].childNodes[0].nodeValue;
name = markers[i].getElementsByTagName("nome")[0].childNodes[0].nodeValue;
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
var html = name + '<br />' + address + '<br />' + city + '<br />' + phone;
var icon = '/images/gmaps/pin_fuc.png';
var marker = new google.maps.Marker({map: map, position: point, icon :'/images/gmaps/pin_fuc.png'});
/*google.maps.event.addListener(marker,"click", function(){
map.panTo(this.position);
});*/
createMarkerButton(marker);
google.maps.event.addListener(marker, "click", function (e) {
ib.open(map);
});
}
});
function createMarkerButton(marker) {
//Creates a sidebar button
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name));
ul.appendChild(li);
//Trigger a click event to marker when the button is clicked.
google.maps.event.addDomListener(li, "mouseover", function(){
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout (function (){marker.setAnimation(null);}, 750);
});
google.maps.event.addDomListener(li, "mouseout", function(){
google.maps.event.trigger(marker, "mouseout");
});
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}