Drawing a path as an object moves on a map - javascript

I have this marker that moves along a google map http://jsfiddle.net/t43kaeyr/ but i need it to draw its path on the map as it moves.
This is the javascript that creates the map
var map,marker;
var startPos = [42.42679066670903, -83.29210638999939];
var speed = 150; // km/h
var delay = 100;
// If you set the delay below 1000ms and you go to another tab,
// the setTimeout function will wait to be the active tab again
// before running the code.
// See documentation :
// https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs
function animateMarker(marker, coords, km_h)
{
var target = 0;
var km_h = km_h || 50;
coords.push([startPos[0], startPos[1]]);
function goToPoint()
{
var lat = marker.position.lat();
var lng = marker.position.lng();
var step = (km_h * 1000 * delay) / 3600000; // in meters
var dest = new google.maps.LatLng(
coords[target][0], coords[target][1]);
var distance =
google.maps.geometry.spherical.computeDistanceBetween(
dest, marker.position); // in meters
var numStep = distance / step;
var i = 0;
var deltaLat = (coords[target][0] - lat) / numStep;
var deltaLng = (coords[target][1] - lng) / numStep;
function moveMarker()
{
lat += deltaLat;
lng += deltaLng;
i += step;
if (i < distance)
{
marker.setPosition(new google.maps.LatLng(lat, lng));
setTimeout(moveMarker, delay);
}
else
{ marker.setPosition(dest);
target++;
if (target == coords.length){ target = 0; }
setTimeout(goToPoint, delay);
}
}
moveMarker();
}
goToPoint();
}
function initialize()
{
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(42.425175091823974, -83.2943058013916),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(startPos[0], startPos[1]),
icon: 'assets/images/c.png',
map: map
});
google.maps.event.addListenerOnce(map, 'idle', function()
{
animateMarker(marker, [
// The coordinates of each point you want the marker to go to.
// You don't need to specify the starting position again.
[42.42666395645802, -83.29694509506226],
[42.42300508749226, -83.29679489135742],
[42.42304468678425, -83.29434871673584],
[42.424882066428424, -83.2944130897522],
[42.42495334300206, -83.29203128814697]
], speed);
});
}
initialize();
I tried drawing the path and the path is drawn correctly but the object does not move any more. This is the code
var map,marker;
var startPos = [42.42679066670903, -83.29210638999939];
var speed = 150; // km/h
var delay = 100;
// If you set the delay below 1000ms and you go to another tab,
// the setTimeout function will wait to be the active tab again
// before running the code.
// See documentation :
// https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs
function animateMarker(marker, coords, km_h)
{
var target = 0;
var km_h = km_h || 50;
coords.push([startPos[0], startPos[1]]);
function goToPoint()
{
var lat = marker.position.lat();
var lng = marker.position.lng();
var step = (km_h * 1000 * delay) / 3600000; // in meters
var dest = new google.maps.LatLng(
coords[target][0], coords[target][1]);
var distance =
google.maps.geometry.spherical.computeDistanceBetween(
dest, marker.position); // in meters
var numStep = distance / step;
var i = 0;
var deltaLat = (coords[target][0] - lat) / numStep;
var deltaLng = (coords[target][1] - lng) / numStep;
function moveMarker()
{
lat += deltaLat;
lng += deltaLng;
i += step;
if (i < distance)
{
marker.setPosition(new google.maps.LatLng(lat, lng));
setTimeout(moveMarker, delay);
}
else
{ marker.setPosition(dest);
target++;
if (target == coords.length){ target = 0; }
setTimeout(goToPoint, delay);
}
}
moveMarker();
}
goToPoint();
}
function initialize()
{
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(42.425175091823974, -83.2943058013916),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(startPos[0], startPos[1]),
icon: 'assets/images/c.png',
map: map
});
var flightPlanCoordinates = [
{lat: 42.42666395645802, lng: -83.29694509506226},
{lat: 42.42300508749226, lng: -83.29679489135742},
{lat: 42.42304468678425, lng: -83.29434871673584},
{lat: 42.424882066428424, lng: -83.2944130897522},
{lat: 42.42495334300206, lng: -83.29203128814697}
];
google.maps.event.addListenerOnce(map, 'idle', function()
{
animateMarker(marker, [
// The coordinates of each point you want the marker to go to.
// You don't need to specify the starting position again.
flightPlanCoordinates
], speed);
});
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
initialize();
How can i make the marker to draw its path as it moves on the map?.

Maybe you want create a Polyline with a Line with multiple points, which represents each position of the marker:
provide a global variable:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var polylineCoords = [];
var path = new google.maps.Polyline({
path: polylineCoords,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
//To add a Point on the polyline call
function addCoord(lat, lng) {
var point = new google.maps.LatLng(lat, lng);
var coords = path.getPath();
coords.push(point);
}
JSFiddle

Related

How to get Google map draw polygon area? [duplicate]

This question already has answers here:
Easiest way to calculate area of drawn polygon with google map
(1 answer)
Calculating area of a polygon drawn on google map
(2 answers)
Closed last month.
I don't have much experience in JavaScript. I am trying to get Area of polygon may be i am doing something wrong. I am using Google API. Every thing working good but unable to get draw polygon area. Below I have also uploaded one image on which I have draw polygon. Can anyone tell me how to find it's area.
var map;
var infoWindow;
var listOfPolygons = [];
var pdata = [
[43.7711057, -79.3696734, "Amritsar"],
[43.7442141, -79.407609, "oyeji"],
[43.7452141, -79.407609, "oyeji"],
];
function initMap() {
var locations = pdata;
var markers = [];
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 43.717899, lng: -79.6582408 },
zoom: 5,
streetViewControl: false,
mapTypeControl: false
});
//Drawing tool
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON,
],
}
})
drawingManager.setMap(map);
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
markers.push(
new google.maps.Marker({
position: {
lat: locations[i][0],
lng: locations[i][1]
},
title:"Amritsar"
})
);
bounds.extend(markers[markers.length - 1].getPosition());
}
map.fitBounds(bounds);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var poly = event.overlay.getPath();
//console.log(poly);
if (event.type == 'polygon') {
// hide polygon from DrawingManager
event.overlay.setMap(null);
//console.log(event.overlay.getPath().getArray());
listOfPolygons.push(new google.maps.Polygon({
paths: event.overlay.getPath().getArray(),
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
//console.log(markers.length);
for (var i = 0; i < markers.length; i++) {
if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), listOfPolygons[listOfPolygons.length - 1])) {
// show current marker
markers[i].setMap(map);
console.log(markers[i].getPosition());
}
}
listOfPolygons[listOfPolygons.length - 1].setMap(map);
listOfPolygons[listOfPolygons.length - 1].addListener('click', showArrays);
}
});
infoWindow = new google.maps.InfoWindow({
content : "Amritsar"
});
/** #this {google.maps.Polygon} */
function showArrays(event) {
// Since this polygon has only one path, we can call getPath() to return the
// MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i = 0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
xy.lng();
}
// Replace the info window's content and position.
//console.log(contentString);
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
}

Circle fade out over time on Google Map [duplicate]

This question already has an answer here:
How do I fade out a circle in a Google Map, x seconds after I've added it to the map?
(1 answer)
Closed 8 years ago.
I am attempting to fade circles out with a setInterval on fillOpacity. However a console log shows the opacity changing but the appearance of the circle does not seem to change. Is there a different set function required to do this?
http://jsfiddle.net/faaxeskg/5/
setInterval(function() {
marker.fillOpacity -= .01;
console.log(marker.fillOpacity);
}, 200);
code snippet:
var map = null;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Add 500 markers to the map at random locations
var southWest = new google.maps.LatLng(-31.203405, 125.244141);
var northEast = new google.maps.LatLng(-25.363882, 131.044922);
var bounds = new google.maps.LatLngBounds(southWest, northEast);
map.fitBounds(bounds);
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
setInterval(function() {
var position = new google.maps.LatLng(
southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
var populationOptions = {
strokeOpacity: 0,
fillColor: '#FF0000',
fillOpacity: 0.65,
map: map,
center: position,
radius: 40000
};
var marker = new google.maps.Circle(populationOptions);
setInterval(function() {
marker.fillOpacity -= .01;
console.log(marker.fillOpacity);
}, 200);
setTimeout(function() {
marker.setMap(null);
delete marker;
}, 30000);
}, 2000);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<div id="map-canvas" style="float:left;width:100%;height:100%;"></div>
You need to associate the "opacity change" to the marker, you can do that with function closure (a createCircleMarker function).
Don't use undocumented properties. Use the documented methods.
marker.set("fillOpacity, marker.get("fillOpacity")-0.01);
working code snippet:
var map = null;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Add 500 markers to the map at random locations
var southWest = new google.maps.LatLng(-31.203405, 125.244141);
var northEast = new google.maps.LatLng(-25.363882, 131.044922);
var bounds = new google.maps.LatLngBounds(southWest, northEast);
map.fitBounds(bounds);
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
setInterval(function() {
var position = new google.maps.LatLng(
southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
var populationOptions = {
strokeOpacity: 0,
fillColor: '#FF0000',
fillOpacity: 0.65,
map: map,
center: position,
radius: 40000
};
createCircleMarker(populationOptions);
}, 2000);
}
function createCircleMarker(populationOptions) {
var marker = new google.maps.Circle(populationOptions);
setInterval(function() {
marker.set("fillOpacity",marker.get("fillOpacity")-0.05);
console.log(marker.fillOpacity);
}, 200);
setTimeout(function() {
marker.setMap(null);
delete marker;
}, 30000);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry"></script>
<div id="map-canvas" style="float:left;width:100%;height:100%;"></div>

Testing Google map.setBounds with Jasmine [duplicate]

I'm writing a code which will:
-- Load a map and center it on a KML
-- Draw a polygon based on the bounds of the map.
Here below the code. I get an error
Uncaught TypeError: Cannot call method 'getNorthEast' of undefined
function initialize()
{
var mapOptions =
{
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP //higer zoom
};
var KML1 = new google.maps.KmlLayer(
{
clickable: false,
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/f43l9uvts1_a.kml' //kml link for the floor-plan
});
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
KML1.setMap(map);
var bounds = new google.maps.LatLngBounds();
bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var QLat = Math.abs((ne.lat()-sw.lat())/5);
var QLng = Math.abs((sw.lng()-ne.lng())/5);
var swLat = sw.lat()+QLat;
var swLng = sw.lng()+QLng;
var neLat = ne.lat()-QLat;
var neLng = ne.lng()-QLng;
ne = new google.maps.LatLng(neLat,neLng);
sw = new google.maps.LatLng(swLat,swLng);
var Coords = [
ne, new google.maps.LatLng(ne.lat(), sw.lng()),
sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
];
surface = new google.maps.Polygon(
{
paths: Coords,
strokeColor: '#00AAFF',
strokeOpacity: 0.6,
strokeWeight: 2,
fillColor: '#00CC66',
fillOpacity: 0.15,
editable: true,
draggable: true,
geodesic:true
});
surface.setMap(map);
google.maps.event.addListener(surface, 'mousemove', ciao) //add listener for changes
//$("#results").append(coordinates[0]);
//Let's update area and price as the poly changes
function ciao(event)
{
var vertices = this.getPath();
// Iterate over the vertices.
for (var i =0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
Coords = []
Coords.push(xy);
};
}
}
Any Suggestion?
Thanks,
Daniele
You need to put all the code that depends on the map bounds inside the event listener.
var surface = null;
function initialize()
{
var mapOptions =
{
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP //higer zoom
};
var KML1 = new google.maps.KmlLayer(
{
clickable: false,
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/f43l9uvts1_a.kml' //kml link for the floor-plan
});
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
KML1.setMap(map);
google.maps.event.addListener(map,'bounds_changed', function()
{
var bounds = new google.maps.LatLngBounds();
bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var QLat = Math.abs((ne.lat()-sw.lat())/5);
var QLng = Math.abs((sw.lng()-ne.lng())/5);
var swLat = sw.lat()+QLat;
var swLng = sw.lng()+QLng;
var neLat = ne.lat()-QLat;
var neLng = ne.lng()-QLng;
ne = new google.maps.LatLng(neLat,neLng);
sw = new google.maps.LatLng(swLat,swLng);
var Coords = [
ne, new google.maps.LatLng(ne.lat(), sw.lng()),
sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
];
surface = new google.maps.Polygon(
{
paths: Coords,
strokeColor: '#00AAFF',
strokeOpacity: 0.6,
strokeWeight: 2,
fillColor: '#00CC66',
fillOpacity: 0.15,
editable: true,
draggable: true,
geodesic:true
});
surface.setMap(map);
}); // end of listener callbck
google.maps.event.addListener(surface, 'mousemove', ciao) //add listener for changes
//$("#results").append(coordinates[0]);
//Let's update area and price as the poly changes
function ciao(event)
{
var vertices = this.getPath();
// Iterate over the vertices.
for (var i =0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
Coords = []
Coords.push(xy);
};
}
} // end of initialize

How to change the marker position in google javascript maps api v3?

I have this map:
.... class Maps ....
Maps.prototype.initialize = function (x, y) {
var latitude = x;
var longitude = y;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: 'Click to zoom'
});
};
Maps.prototype.changePosition = function (x, y) {
var latitude = x;
var longitude = y;
var map = new google.maps.LatLng(latitude, longitude);
marker.setPosition(map);
}
....
then:
var maps = new Maps();
var marker = maps.initialize(x, y);
window.setTimeout(function() {
maps.changePosition(x, y));
}, 3000);
the initialize method works, and renders the map and the marker
but the second one doesn't work, doesn't know what setPosition is
any ideas on this issue?
There are different issues.
the first one, which will prevent the code from executing: your iinitialize-function doesn't have a return-value, so your maps-variable is undefined and didn't have a method changePosition.
Later: the changePosition has to arguments , z and y , but inside the function you access the variables x and y
However, I don't see any code that modifies x and y , so even when the code would work it doesn't have any visible effect.
function Maps(){}
Maps.prototype.initialize = function (x, y, z, o) {
this.center = new google.maps.LatLng(x, y)
this.zoom = z;
this.node = document.getElementById(o);
this.markers = [];
var mapOptions = {
zoom: this.zoom,
center: this.center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(this.node, mapOptions);
return this;
};
Maps.prototype.addMarker=function(x, y, t , c){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(x,y),
map: this.map,
title: t||'Click to zoom'
});
this.markers.push(marker);
if(c)this.map.setCenter(marker.getPosition());
return marker;
}
Maps.prototype.changePosition = function (m , x, y, c, f) {
var latLng = new google.maps.LatLng(x, y);
m.setPosition(latLng);
if(c)this.map.setCenter(latLng);
if(f)f();
}
//create the Maps-instance
var maps = new Maps(),
x = 10,
y = 10;
//do something onload
google.maps.event.addDomListener(window,'load',function(){
//initialize maps
maps.initialize(x, y , 3, 'map_canvas');
//add a marker
var marker=maps.addMarker(x, y ,'hello marker', true);
//change position of marker
window.setTimeout(function() {
maps.changePosition(marker, x+50, y+50 ,true,
function(){alert('position changed');});
}, 5000);
});

.gif marker google maps

I have in my code this
var map;
function initialize() {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);
}
function addMarkers() {
var iconoMarca = "/assets/giftRayo.gif");
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
for (var i = 0; i < 10; i++) {
var latLng = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: iconoMarca
});
}
}
but the marker doesn't appear and if I use a png or jpeg it works. What am I doing wrong?? Do the gif animations have another treatment?
As a standard, the markers use something called optimized rendering that always renders the markers as static. To see animated gifs you need to set optimized = false on your marker. The code for generating your marker would then be:
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: iconoMarca,
optimized: false
});
This should solve your problem.
Ps.:
You seem to have a small bug in your code:
var iconoMarca = "/assets/giftRayo.gif");
You should remove the ).

Categories

Resources