i just want to show a track on my map i tried as follow but the problem is i don't want to load track point in layer from GPX File (because i don't want to generate file from coordinates witch i get from GPSdevice programmatically)
is there any way to add a track layer from long and lat
// Add the Layer with the GPX Track
var lgpx = new OpenLayers.Layer.Vector("Car track", {
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: "testTrack.GPX",
format: new OpenLayers.Format.GPX()
}),
style: { strokeColor: "green", strokeWidth: 5, strokeOpacity: 0.5 },
projection: new OpenLayers.Projection("EPSG:4326")
});
map.addLayer(lgpx);
Here is the lat and long in GPX file(xml format)
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.0">
<name>Example gpx</name>
<trk><name>Example gpx</name><number>1</number>
<trkseg>
<trkpt lat="35.737097" lon="51.314965"></trkpt>
<trkpt lat="35.736953" lon="51.317454"></trkpt>
<trkpt lat="35.737572" lon="51.317551"></trkpt>
<trkpt lat="35.737755" lon="51.315716"></trkpt>
<trkpt lat="35.739588" lon="51.316070"></trkpt>
</trkseg>
</trk>
</gpx>
i've found the solution ,here it is
lineLayer = new OpenLayers.Layer.Vector("Line Layer");
map.addLayer(lineLayer);
map.addControl(new OpenLayers.Control.DrawFeature(lineLayer, OpenLayers.Handler.Path));
var coordinates = [
{ lat: "35.737097", lon: "51.314965" },
{ lat: "35.736953", lon: "51.317454" },
{ lat: "35.737572", lon: "51.317551" },
{ lat: "35.737755", lon: "51.315716" },
{ lat: "35.739588", lon: "51.316070" }
];
function DrawTrack(){
var points = coordinates.map(function (cor) {
return new OpenLayers.Geometry.Point(cor.lon, cor.lat)
.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
});
var style = {
strokeColor: '#0000ff',
strokeOpacity: 0.5,
strokeWidth: 5
};
for (var i = 0; i < points.length - 1; i++) {
(function (i) {
window.setTimeout(function () {
var line = new OpenLayers.Geometry.LineString([points[i], points[i + 1]]);
var lineFeature = new OpenLayers.Feature.Vector(line, null, style);
lineLayer.addFeatures([lineFeature]);
map.setCenter(points[i].lon, points[i].lat);
}, i * 1000);
}(i));
}
}
Example of loading GPX data in OpenLayers 3.
var lgpx = new ol.layer.Vector({
title: 'Car track',
source: new ol.source.Vector({
url: 'testTrack.gpx',
format: new ol.format.GPX()
}),
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 5,
opacity: 0.5
})
})
});
map.addLayer(lgpx);
List of available formats.
Your answer was closed to be perfect.
You must parse the string number to float.
lineLayer = new OpenLayers.Layer.Vector("Line Layer");
map.addLayer(lineLayer);
map.addControl(new OpenLayers.Control.DrawFeature(lineLayer,
OpenLayers.Handler.Path));
var coordinates = [
{ lat: "35.737097", lon: "51.314965" },
{ lat: "35.736953", lon: "51.317454" },
{ lat: "35.737572", lon: "51.317551" },
{ lat: "35.737755", lon: "51.315716" },
{ lat: "35.739588", lon: "51.316070" }
];
function DrawTrack(){
var points = coordinates.map(function (cor) {
return new OpenLayers.Geometry.Point(parseFloat(cor.lon),parseFloat(cor.lat))
.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
});
var style = {
strokeColor: '#0000ff',
strokeOpacity: 0.5,
strokeWidth: 5
};
for (var i = 0; i < points.length - 1; i++) {
(function (i) {
window.setTimeout(function () {
var line = new OpenLayers.Geometry.LineString([points[i], points[i + 1]]);
var lineFeature = new OpenLayers.Feature.Vector(line, null, style);
lineLayer.addFeatures([lineFeature]);
map.setCenter(points[i].lon, points[i].lat);
}, i * 1000);
}(i));
}
}
Related
I want to loop through an array of coordinates that I want to use for markers and drawing a line in google maps.
Is there a solution to create the path property with a loop of const locations?
Please check my example below:
const lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "red",
scale: 4
};
const locations = [
["Tampere", 61.50741562413278, 23.75886761967578, 1, "Termin: xx.xx"],
["Helsinki", 60.219957, 25.196776, 2, "test2"],
["Travemünde", 55.778989, 18.271974, 2, "test3"],
["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
["Ludwigsburg", 48.8893286910321, 9.197454231637288, 4, "test5"],
]
const line = new google.maps.Polyline({
path: [
{ lat: locations[0][1], lng: locations[0][2] },
{ lat: 60.219957, lng: 25.196776 },
{ lat: locations[2][1], lng: locations[2][2] },
{ lat: 53.941362, lng: 10.860464 },
{ lat: 48.7733567672875, lng: 9.174572759931003 },
],
strokeColor: "red",
scale: 7,
icons: [
{
icon: lineSymbol,
offset: "100%",
},
],
map: map,
});
By using above code it creates in Google Maps this:
The result
To process your input array and create a polyline in a loop:
var path = [];
for (var i=0; i<locations.length; i++) {
// add to polyline
path.push({lat: locations[i][2], lng: locations[i][1]});
// create marker
new google.maps.Marker({
position: path[path.length-1],
map: map
})
}
const line = new google.maps.Polyline({
path: path,
strokeColor: "red",
scale: 7,
icons: [
{
icon: lineSymbol,
offset: "100%",
},
],
map: map,
});
proof of concept fiddle
(note that the data in your question doesn't match your picture)
code snippet:
// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: "terrain",
});
const lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "red",
scale: 4
};
const locations = [
["Tampere", 61.50741562413278, 23.75886761967578, 1, "Termin: xx.xx"],
["Helsinki", 60.219957, 25.196776, 2, "test2"],
["Travemünde", 55.778989, 18.271974, 2, "test3"],
["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
["Ludwigsburg", 48.8893286910321, 9.197454231637288, 4, "test5"],
]
var path = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
path.push({
lat: locations[i][2],
lng: locations[i][1]
});
bounds.extend(path[path.length - 1]);
new google.maps.Marker({
position: path[path.length - 1],
map: map
})
}
const line = new google.maps.Polyline({
path: path,
strokeColor: "red",
scale: 7,
icons: [{
icon: lineSymbol,
offset: "100%",
}, ],
map: map,
});
map.fitBounds(bounds);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Polylines</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>
I tried something like this
<script charset="utf-8">
var request = new XMLHttpRequest();
// request.open("POST", "https://localhost:8443/control/jqxGeneralServicer?sname=JQGetListCustomerByCluster&deliveryClusterId=120120", false);
request.open("POST", "https://localhost:8443/control/jqxGeneralServicer?sname=JQGetListCustomerByCluster&deliveryClusterId=${deliveryCluster.deliveryClusterId}", false);
// ${deliveryCluster.deliveryClusterId}
request.setRequestHeader('Content-Type', 'application/json');
request.send(null);
var foo = request.responseText;
var json = JSON.parse(foo);
// console.log(json["results"][0]);
var labels = new Array();
var locations = new Array();
for(i = 0; i < json["results"].length; i++){
labels.push(json["results"][i]["fullName"]);
locacations["lng"] = json["results"][i]["longitude"];
locacations["lat"] = json["results"][i]["latitude"];
}
// console.log(labels) ;
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 16,
center: {lat: 20.993514917846174, lng: 105.78660475957122},
});
// const labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//const labels = [
// "Cửa hàng Quang Anh",
// "Cửa hàng Quang Em",
// "Cửa hàng Hưng Thịnh",
// "Cửa hàng Cửa hàng Thành Hưng"];
var locations = [
{ lat: 20.9935851166474, lng: 105.78857910579417 },
{ lat: 20.986910834987295, lng: 105.78535398147808 },
{ lat: 20.990339683019226, lng: 105.7922698253056 },
{ lat: 20.996770381033244, lng: 105.79321396285934 }
];
const markers = locations.map((location, i) => {
return new google.maps.Marker({
position: location,
label: labels[i],
//label: labels[i % labels.length],
});
});
new MarkerClusterer(map, markers, {
imagePath:
"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
});
const ecolife = {lat: 20.993514917846174, lng: 105.78660475957122};
// const map22 = new google.maps.Map(document.getElementById("map"), {
// zoom: 18,
// center: ecolife,
// });
// const marker = new google.maps.Marker({
// position: ecolife,
// map: map22,
// });
}
</script>
<div id="map" style="height: 400px; width: 100%; margin: 0px 10px 10px 10px;"></div>
Please guide me set value for var locations from json data source.
These line is not satisfy me (but I don't know how to change it)
for(i = 0; i < json["results"].length; i++){
labels.push(json["results"][i]["fullName"]);// this line is ok for variable `labels`
locacations["lng"] = json["results"][i]["longitude"]; // these lines is not ok
locacations["lat"] = json["results"][i]["latitude"]; // these lines is not ok.
}
//
The true format must be like the sample from Google Maps
const locations = [
{ lat: 20.9935851166474, lng: 105.78857910579417 },
{ lat: 20.986910834987295, lng: 105.78535398147808 },
{ lat: 20.990339683019226, lng: 105.7922698253056 },
{ lat: 20.996770381033244, lng: 105.79321396285934 }
];
Just push an object instead:
locations.push({lng: json['results'][i]['longitude'], lat: json['results'][i]['latitude']});
beware that you shouldn't use synchronous http requests.
I have created a webpage which uses Google Map API.
JSfiddle
function initMap() {
var intervalForAnimation;
var count = 0;
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 19.0760, lng: 72.8777},
zoom: 5,
styles: [
{
featureType: 'all',
stylers: [
{ saturation: -80 }
]
},{
featureType: 'road.arterial',
elementType: 'geometry',
stylers: [
{ hue: '#00ffee' },
{ saturation: 50 }
]
},{
featureType: 'poi.business',
elementType: 'labels',
stylers: [
{ visibility: 'off' }
]
}
]
});
// Define the symbol, using one of the predefined paths ('CIRCLE')
// supplied by the Google Maps JavaScript API.
var symbolSource = {
path: 'M -2,-2 2,2 M 2,-2 -2,2',
strokeColor: '#FF0000',
strokeWeight: 4
};
var symbolShape = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: '#0000FF',
strokeOpacity: 1.0
};
var symbolDestination = {
path: 'M -2,-2 2,2 M 2,-2 -2,2',
strokeColor: '#292',
strokeWeight: 4
};
// Create the polyline and add the symbol to it via the 'icons' property.
var line = new google.maps.Polyline({
path: [{lat: -33.918861, lng: 18.423300}, {lat: -35.842160, lng: 18.863525}, {lat: -39.170387, lng: 35.189209}, {lat: -26.331494, lng: 54.228516}, {lat: 0.462885, lng: 61.083984}, {lat: 19.075984, lng: 72.877656}],
icons: [
{
icon: symbolShape,
offset: '0%'
}
],
strokeColor: '#0000FF ',
strokeOpacity: 0,
map: map
});
//Our Secondary polyline for reseting purpose
var line1 = new google.maps.Polyline({
path: [{lat: -33.918861, lng: 18.423300}, {lat: -35.842160, lng: 18.863525}, {lat: -39.170387, lng: 35.189209}, {lat: -26.331494, lng: 54.228516}, {lat: 0.462885, lng: 61.083984}, {lat: 19.075984, lng: 72.877656}],
icons: [
{
icon: symbolSource,
offset: '0%'
}, {
icon: symbolDestination,
offset: '100%'
}
],
strokeColor: '#0000FF ',
strokeOpacity: 0.8,
map: map
});
//Map boundaries
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < line.getPath().getLength(); i++) {
bounds.extend(line.getPath().getAt(i));
}
map.fitBounds(bounds);
function playing() {
intervalForAnimation = window.setInterval(function() {
$("#map").after(animateCircle(line,count));
count = (count+0.2) % 200;
}, 20);
}
$(".play").click(function() {
playing();
pb = new progressBar();
map.controls[google.maps.ControlPosition.RIGHT].push(pb.getDiv());
});
$(".pause").click(function() {
clearInterval(intervalForAnimation);
});
$(".reset").click(function(){
count = 0;
line1.setMap(map);
});
// Use the DOM setInterval() function to change the offset of the symbol
// at fixed intervals.
function animateCircle(line,count) {
var icons = line.get('icons');
//if ((icons[0].offset <= 100 + '%')) {
icons[0].offset = (count / 2) + '%';
line.set('icons', icons);
if (count >= 199){
clearInterval(intervalForAnimation);
line1.setMap(null);
};
//n++;
//};
}
}
var intervalForAnimation;
var count = 0;
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 19.0760, lng: 72.8777},
zoom: 5,
styles: [
{
featureType: 'all',
stylers: [
{ saturation: -80 }
]
},{
featureType: 'road.arterial',
elementType: 'geometry',
stylers: [
{ hue: '#00ffee' },
{ saturation: 50 }
]
},{
featureType: 'poi.business',
elementType: 'labels',
stylers: [
{ visibility: 'off' }
]
}
]
});
// Define the symbol, using one of the predefined paths ('CIRCLE')
// supplied by the Google Maps JavaScript API.
var symbolSource = {
path: 'M -2,-2 2,2 M 2,-2 -2,2',
strokeColor: '#FF0000',
strokeWeight: 4
};
var symbolShape = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: '#0000FF',
strokeOpacity: 1.0
};
var symbolDestination = {
path: 'M -2,-2 2,2 M 2,-2 -2,2',
strokeColor: '#292',
strokeWeight: 4
};
// Create the polyline and add the symbol to it via the 'icons' property.
var line = new google.maps.Polyline({
path: [{lat: -33.918861, lng: 18.423300}, {lat: -35.842160, lng: 18.863525}, {lat: -39.170387, lng: 35.189209}, {lat: -26.331494, lng: 54.228516}, {lat: 0.462885, lng: 61.083984}, {lat: 19.075984, lng: 72.877656}],
icons: [
{
icon: symbolShape,
offset: '0%'
}
],
strokeColor: '#0000FF ',
strokeOpacity: 0,
map: map
});
//Our Secondary polyline for reseting purpose
var line1 = new google.maps.Polyline({
path: [{lat: -33.918861, lng: 18.423300}, {lat: -35.842160, lng: 18.863525}, {lat: -39.170387, lng: 35.189209}, {lat: -26.331494, lng: 54.228516}, {lat: 0.462885, lng: 61.083984}, {lat: 19.075984, lng: 72.877656}],
icons: [
{
icon: symbolSource,
offset: '0%'
}, {
icon: symbolDestination,
offset: '100%'
}
],
strokeColor: '#0000FF ',
strokeOpacity: 0.8,
map: map
});
//Map boundaries
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < line.getPath().getLength(); i++) {
bounds.extend(line.getPath().getAt(i));
}
map.fitBounds(bounds);
function playing() {
intervalForAnimation = window.setInterval(function() {
$("#map").after(animateCircle(line,count));
count = (count+0.2) % 200;
}, 20);
}
$(".play").click(function() {
playing();
pb = new progressBar();
map.controls[google.maps.ControlPosition.RIGHT].push(pb.getDiv());
});
$(".pause").click(function() {
clearInterval(intervalForAnimation);
});
$(".reset").click(function(){
count = 0;
line1.setMap(map);
});
// Use the DOM setInterval() function to change the offset of the symbol
// at fixed intervals.
function animateCircle(line,count) {
var icons = line.get('icons');
//if ((icons[0].offset <= 100 + '%')) {
icons[0].offset = (count / 2) + '%';
line.set('icons', icons);
if (count >= 199){
clearInterval(intervalForAnimation);
line1.setMap(null);
};
}
}
The Webpage SS
I want to implement a slider which has the limits of the date given by user to it. And the slider should be interactive ie the user can jump forward or backward just by clicking on the slider line eg the slider used in YouTube.
Note:Implementation of slider and controlling the animation of the symbol with the slider line is primary objective. Setting the limits is secondary objective.
I tried implementing it,but wasn't able to get success.
One option would be to use the jquery-ui slider (from this question: control the animation of the symbol via a slider (in google maps)):
$(function() {
$("#slider").slider({
max: 200,
min: 0,
change: function(event, ui) {
console.log("ui.value=" + ui.value);
var icons = line.get('icons');
icons[0].offset = (ui.value / 2) + '%';
line.set('icons', icons);
}
});
});
proof of concept fiddle
code snippet:
var line;
var line1;
function initMap() {
var intervalForAnimation;
var count = 0;
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 19.0760,
lng: 72.8777
},
zoom: 5,
styles: [{
featureType: 'all',
stylers: [{
saturation: -80
}]
}, {
featureType: 'road.arterial',
elementType: 'geometry',
stylers: [{
hue: '#00ffee'
}, {
saturation: 50
}]
}, {
featureType: 'poi.business',
elementType: 'labels',
stylers: [{
visibility: 'off'
}]
}]
});
// Define the symbol, using one of the predefined paths ('CIRCLE')
// supplied by the Google Maps JavaScript API.
var symbolSource = {
path: 'M -2,-2 2,2 M 2,-2 -2,2',
strokeColor: '#FF0000',
strokeWeight: 4
};
var symbolShape = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: '#0000FF',
strokeOpacity: 1.0
};
var symbolDestination = {
path: 'M -2,-2 2,2 M 2,-2 -2,2',
strokeColor: '#292',
strokeWeight: 4
};
// Create the polyline and add the symbol to it via the 'icons' property.
line = new google.maps.Polyline({
path: [{
lat: -33.918861,
lng: 18.423300
}, {
lat: -35.842160,
lng: 18.863525
}, {
lat: -39.170387,
lng: 35.189209
}, {
lat: -26.331494,
lng: 54.228516
}, {
lat: 0.462885,
lng: 61.083984
}, {
lat: 19.075984,
lng: 72.877656
}],
icons: [{
icon: symbolShape,
offset: '0%'
}],
strokeColor: '#0000FF ',
strokeOpacity: 0,
map: map
});
//Our Secondary polyline for reseting purpose
var line1 = new google.maps.Polyline({
path: [{
lat: -33.918861,
lng: 18.423300
}, {
lat: -35.842160,
lng: 18.863525
}, {
lat: -39.170387,
lng: 35.189209
}, {
lat: -26.331494,
lng: 54.228516
}, {
lat: 0.462885,
lng: 61.083984
}, {
lat: 19.075984,
lng: 72.877656
}],
icons: [{
icon: symbolSource,
offset: '0%'
}, {
icon: symbolDestination,
offset: '100%'
}],
strokeColor: '#0000FF ',
strokeOpacity: 0.8,
map: map
});
//Map boundaries
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < line.getPath().getLength(); i++) {
bounds.extend(line.getPath().getAt(i));
}
map.fitBounds(bounds);
function playing() {
intervalForAnimation = window.setInterval(function() {
$("#map").after(animateCircle(line, count));
count = (count + 0.2) % 200;
}, 20);
}
$(".play").click(function() {
playing();
pb = new progressBar();
map.controls[google.maps.ControlPosition.RIGHT].push(pb.getDiv());
});
$(".pause").click(function() {
clearInterval(intervalForAnimation);
});
$(".reset").click(function() {
count = 0;
line1.setMap(map);
});
// Use the DOM setInterval() function to change the offset of the symbol
// at fixed intervals.
function animateCircle(line, count) {
var icons = line.get('icons');
//if ((icons[0].offset <= 100 + '%')) {
icons[0].offset = (count / 2) + '%';
line.set('icons', icons);
$("#slider").slider("value", count);
if (count >= 199) {
clearInterval(intervalForAnimation);
// line1.setMap(null);
};
//n++;
//};
}
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script>
$(function() {
$("#slider").slider({
max: 200,
min: 0,
change: function(event, ui) {
console.log("ui.value=" + ui.value);
var icons = line.get('icons');
//if ((icons[0].offset <= 100 + '%')) {
icons[0].offset = (ui.value / 2) + '%';
line.set('icons', icons);
}
});
});
</script>
<script>
$(document).ready(function() {
$("#datepickerFrom").datepicker();
});
</script>
<div style="border: 1px solid black; background-color: green; padding: 5px;">
slider
<div id="slider"></div>
</div>
<div>
<!--Play button-->
<button type="button" class="play">Play</button>
<!--Pause button-->
<button type="button" class="pause">Pause</button>
<!--Reset and Stop button-->
<button type="button" class="reset">Reset</button>
</div>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
I'm using this functions to get markers via Ajax, and draw it in a map_canvas div. That works perfectly, and I'm trying to reuse the "gmarkers" variable to create a heatmap...with no luck. How can I create a heatmap with this data?
I prefer to use the same data I'm loading with this function weighting the heatmap by variable: llamados.
How can I start?
var gmarkers = [];
function initialize() {
var myOptions = {
zoom: 10,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
current_zoom = map.getZoom();
var myControl = document.getElementById('descripcion');
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(myControl);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var marker, i;
var myLatLng;
function CreateMarker (obj, i) {
myLatLng = new google.maps.LatLng(obj['lat'], obj['lon']);
marker = new google.maps.Marker({
position: myLatLng,
animation: google.maps.Animation.DROP,
title: obj['nodo'],
llamados: obj['llamados'],
icon: obj['icono'],
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('Nodo: ' + obj['nodo'] + '; Llamados: ' + obj['llamados']);
infowindow.open(map, marker);
}
})(marker, i));
gmarkers.push(marker);
}
function ejecutarAjax(){
$.ajax({
beforeSend: function() {
},
cache: false,
// data: params,
dataType: 'json',
timeout: 0,
type: 'POST',
url: 'traerLlamados.php',
success: function(data) {
if (data) {
var data = data;
var obj;
cantidad=Object.keys(data).length;
for(var i in data){
CreateMarker(data[i]);
};
}
else {
alert('No data');
}
},
});
}
Given your existing code, you should be able to add a heatmap to the map (after the markers are loaded) by doing:
var heatmapArray = [];
for (var i=0; i<gmarkers.length; i++) {
heatmapArray.push({location: gmarkers[i].getPosition(), weight: gmarkers[i].llamados});
}
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapArray
});
heatmap.setMap(map);
Proof of concept fiddle
Code snippet:
var gmarkers = [];
var mapCenter = new google.maps.LatLng(37.782, -122.447);
function initialize() {
var myOptions = {
zoom: 15,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
current_zoom = map.getZoom();
var myControl = document.getElementById('descripcion');
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(myControl);
for (var i = 0; i < heatMapData.length; i++) {
// Translate into obj expected by CreateMarker
var obj = {
lat: heatMapData[i].location.lat(),
lon: heatMapData[i].location.lng(),
nodo: "nodo" + i,
llamados: heatMapData[i].weight,
icono: "http://maps.google.com/mapfiles/ms/micons/blue.png"
}
CreateMarker(obj, i);
}
var heatmapArray = [];
for (var i = 0; i < gmarkers.length; i++) {
heatmapArray.push({
location: gmarkers[i].getPosition(),
weight: gmarkers[i].llamados
});
}
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapArray
});
heatmap.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var marker, i;
var myLatLng;
function CreateMarker(obj, i) {
myLatLng = new google.maps.LatLng(obj['lat'], obj['lon']);
marker = new google.maps.Marker({
position: myLatLng,
animation: google.maps.Animation.DROP,
title: obj['nodo'],
llamados: obj['llamados'],
icon: obj['icono'],
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('Nodo: ' + obj['nodo'] + '; Llamados: ' + obj['llamados']);
infowindow.open(map, marker);
}
})(marker, i));
gmarkers.push(marker);
}
google.maps.event.addDomListener(window, "load", initialize);
/* Data points defined as a mixture of WeightedLocation and LatLng objects */
var heatMapData = [{
location: new google.maps.LatLng(37.782, -122.447),
weight: 0.5
}, {
location: new google.maps.LatLng(37.782, -122.445),
weight: 1
}, {
location: new google.maps.LatLng(37.782, -122.443),
weight: 2
}, {
location: new google.maps.LatLng(37.782, -122.441),
weight: 3
}, {
location: new google.maps.LatLng(37.782, -122.439),
weight: 2
}, {
location: new google.maps.LatLng(37.782, -122.437),
weight: 10
}, {
location: new google.maps.LatLng(37.782, -122.435),
weight: 0.5
}, {
location: new google.maps.LatLng(37.785, -122.447),
weight: 3
}, {
location: new google.maps.LatLng(37.785, -122.445),
weight: 2
}, {
location: new google.maps.LatLng(37.785, -122.443),
weight: 5
}, {
location: new google.maps.LatLng(37.785, -122.441),
weight: 0.5
}, {
location: new google.maps.LatLng(37.785, -122.439),
weight: 1
}, {
location: new google.maps.LatLng(37.785, -122.437),
weight: 2
}, {
location: new google.maps.LatLng(37.785, -122.435),
weight: 3
}];
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,visualization"></script>
<div id="map_canvas"></div>
I am using the google maps api and using grid clustering for the markers. I wanted to know if there is a way to exclude a single marker from clustering. I want a "You are here" marker that is always visible. I tried using a different array for just that marker and not including it the cluster function but that didn't work.
Does anyone have a solution for this?
Here is how i am doing the clustering
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [], markers_data = [], markers_data2 = [], fred, clust1, markss;
you_are_here.push({
lat : Geo.lat,
lng : Geo .lng,
animation: google.maps.Animation.DROP,
title : 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
}
});
function loadResults (data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++)
{
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined)
{
markers_data.push({
lat : item.Lat,
lng : item.Lng,
title : item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map.addMarkers(markers_data);
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 10,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50
}
clust1 = new MarkerClusterer(map,[], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(you_are_here);
The GMaps clusters all the markers you add to it with the addMarker method (if you provide a MarkerClusterer).
One option: add your "special" marker (the one that you don't want clustered) to the map manually, so it isn't added to the MarkerClusterer:
The GMaps.map property is a reference to the Google Maps Javascript API v3 map object. So this will add a marker to the map without letting the GMaps library know about it:
you_are_here = new google.maps.Marker({
position: {lat: Geo.lat,lng: Geo.lng},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
map: map.map
});
proof of concept fiddle
code snippet:
var Geo = {
lat: 40.7281575,
lng: -74.07764
};
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [],
markers_data = [],
markers_data2 = [],
fred, clust1, markss;
function loadResults(data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++) {
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined) {
markers_data.push({
lat: item.Lat,
lng: item.Lng,
title: item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 8,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50,
imagePath: "https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m"
}
clust1 = new MarkerClusterer(map, [], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(markers_data);
you_are_here = new google.maps.Marker({
position: {
lat: Geo.lat,
lng: Geo.lng
},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
},
map: map.map
});
// map.addMarkers(you_are_here);
}
loadResults(data);
});
var data = {
map: [{
Lat: 40.7127837,
Lng: -74.005941,
Site: "New York, NY",
distance: 1
}, {
Site: "Newark, NJ",
Lat: 40.735657,
Lng: -74.1723667,
distance: 2
}]
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://rawgit.com/HPNeo/gmaps/master/gmaps.js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/src/markerclusterer.js"></script>
<input id="mapbut" type="button" value="map" />
<div id="map"></div>
To get around this is relatively simple, just after I send the markers array to MarkerClusterer I then add my location.
// Setup cluster markers
var markerCluster = new MarkerClusterer( gmap.map, options )
// add my location
gmap.addMarker({
lat: data.latitude,
lng: data.longitude
...
})
Thanks