I'm trying to start a live tracking via google maps fetching new locations from a database via ajax and it works fine but the problem is with drawing Polylines I get this error "InvalidValueError: at index 0: not a LatLng or LatLngLiteral: not an Object" which means the "line" variable value can't be used as a point as in here google maps link. Here's the code
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
function autoUpdate() {
$.post('ajax/track.php',{car:'1'}).done(function (data) {
var parsed = JSON.parse(data);
var lat = parsed.lat,
lon = parsed.lon;
var newPoint = new google.maps.LatLng(lat,lon);
var line = "{lat: "+lat+", lng: "+lon+"},";
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
var flightPlanCoordinates = [
];
flightPlanCoordinates.push(line);
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
else {
marker = new google.maps.Marker({
position: newPoint,
map: map,
icon: 'images/1.png',
});
}
map.setCenter(newPoint);
});
setTimeout(autoUpdate, 5000);
}
autoUpdate();
UPDATE as suggested by #geocodezip:
var line = {lat: lat, lng: lon};
I got this error "InvalidValueError: at index 0: not a LatLng or LatLngLiteral: in property lat: not a number" so I changed it into
var line = {lat: parseFloat(lat), lng: parseFloat(lon)};
in console I get the last location only not an array of locations
The error is telling you that this:
var line = "{lat: "+lat+", lng: "+lon+"},";
Is not a google.maps.LatLng or a google.maps.LatLngLiteral, because it isn't, it is a string.
This would be a valid google.maps.LatLngLiteral:
var line = {lat: lat, lng: lon};
proof of concept fiddle
code snippet:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
var initlat = 42;
var initlon = -72;
var increment = 0.001;
var count = 0;
var flightPlanCoordinates = [];
function autoUpdate() {
/* $.post('ajax/track.php', {
car: '1'
}).done(function(data) { */
data = JSON.stringify({
lat: +(initlat + increment * count),
lon: +(initlon + increment * count)
});
// data = "{lat:" + (initlat + increment * count) + ",lon:" + (initlon + increment * count) + "}";
count++;
var parsed = JSON.parse(data);
var lat = parsed.lat,
lon = parsed.lon;
var newPoint = new google.maps.LatLng(lat, lon);
// var line = "{lat: " + lat + ", lng: " + lon + "},";
var line = {
lat: lat,
lng: lon
};
flightPlanCoordinates.push(line);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
} else {
marker = new google.maps.Marker({
position: newPoint,
map: map,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
}
});
}
map.setCenter(newPoint);
// });
setTimeout(autoUpdate, 5000);
}
autoUpdate();
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
Related
i want to draw a polygon on the trigger of certain function. i have created a button submit which initiate the insert function which got coordinates from the user and call display function.
var map; var triangleCoords = [];
function insert() {
//var markerImage = 'assets/img/marker.png';
// var marker = new google.maps.Marker({
// position: location,
// map: map,
// icon: markerImage
// });
triangleCoords = [
[30.983611, 73.332778],
[30.93361111, 73.33055556],
[30.93361111, 73.43055556],
[30.98111111, 73.42944444]
];
display();
}
function display()
{
function initMap() {
var location = new google.maps.LatLng(31.1704, 72.7097);
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: location,
zoom: 7,
panControl: false
// mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var points = [];
for (var i = 0; i < triangleCoords.length; i++) {
points.push({
lat: triangleCoords[i][0],
lng: triangleCoords[i][1]
});
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: points,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
zoom: 13,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}
google.maps.event.addDomListener(window,'load',initMap);
}
code is working fine but if i remove google.maps.event.addDomListener(window,'load',initMap); line map doesnot display. my submit button clears the forms.
I am working on google map polygon marker, I have predefined lat long array, and need to set polygon area, It is working fine for me, but when i drag the marker polygon line doesn't change, it should have to be change as i drag the marker, can anyone please help me how can i resolve this issue ? Here i have added my code, can anyone please help me ?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Polygon Arrays</title>
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
<input type="text" name="estimated_area" id="estimated_area" value="">
<input type="text" name="field_fj0d6" id="field_fj0d6" value="">
<script>
// This example creates a simple polygon representing the Bermuda Triangle.
// When the user clicks on the polygon an info window opens, showing
// information about the polygon's coordinates.
var map;
var infoWindow;
var markers = []; // Store Marker in an Array
function initMap() {
var lM = 't';
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 24.886, lng: -70.268},
mapTypeId: 'terrain'
});
// Define the LatLng coordinates for the polygon.
var triangleCoords = [
{lat: 25.774, lng: -80.190},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757}
];
// Add Markers to Coordinates
for (var i = 0; i < triangleCoords.length; i++) {
var pos = triangleCoords[i];
var marker = new google.maps.Marker({
map: map,
position: pos,
draggable: true,
});
marker.setMap(map);
markers.push(marker);
var measure = {
mvcLine: new google.maps.MVCArray(),
mvcPolygon: new google.maps.MVCArray(),
mvcMarkers: new google.maps.MVCArray(),
line: null,
polygon: null
};
var latLng = pos;
var dot = marker;
/************** New Code ****************/
measure.mvcLine.push(latLng);
measure.mvcPolygon.push(latLng);
measure.mvcMarkers.push(dot);
var latLngIndex = measure.mvcLine.getLength() - 1;
google.maps.event.addListener(dot, "drag", function (evt) {
measure.mvcLine.setAt(latLngIndex, evt.latLng);
measure.mvcPolygon.setAt(latLngIndex, evt.latLng);
});
google.maps.event.addListener(dot, "dragend", function () {
console.log('<p>Marker dropped: Current Lat: ' + this.getPosition().lat() + ' Current Lng: ' + this.getPosition().lng() + '</p>');
drag = true;
setTimeout(function () {
drag = false;
}, 250);
if (measure.mvcLine.getLength() > 1) {
mC();
}
});
if (measure.mvcLine.getLength() > 1) {
if (!measure.line) {
measure.line = new google.maps.Polyline({
map: map,
clickable: false,
strokeColor: "#ff5b06",
strokeOpacity: 1,
strokeWeight: 3,
path: measure.mvcLine
});
}
if (measure.mvcPolygon.getLength() > 2) {
if (!measure.polygon) {
if (lM) {
measure.polygon = new google.maps.Polygon({
clickable: false,
map: map,
fillOpacity: 0.6,
fillColor: '#000000',
strokeOpacity: 0,
paths: measure.mvcPolygon
});
} else {
measure.polygon = new google.maps.Polygon({
clickable: false,
map: map,
fillOpacity: 0.6,
fillColor: '#000000',
strokeOpacity: 0,
paths: measure.mvcPolygon
});
}
}
}
}
if (measure.mvcLine.getLength() > 1) {
mC();
}
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#ff5b06',
strokeOpacity: 1,
strokeWeight: 3,
fillColor: '#000000',
fillOpacity: 0.6
});
bermudaTriangle.setMap(map);
}
function mR() {
if (measure.polygon) {
measure.polygon.setMap(null);
measure.polygon = null;
}
if (measure.line) {
measure.line.setMap(null);
measure.line = null
}
measure.mvcLine.clear();
measure.mvcPolygon.clear();
measure.mvcMarkers.forEach(function (elem, index) {
elem.setMap(null);
});
measure.mvcMarkers.clear();
document.getElementById('estimated_area').value = '';
document.getElementById('field_fj0d6').value = '';
}
function mC() {
var l = 0;
if (measure.mvcPolygon.getLength() > 1) {
l = google.maps.geometry.spherical.computeLength(measure.line.getPath());
}
var a = 0;
if (measure.mvcPolygon.getLength() > 2) {
a = google.maps.geometry.spherical.computeArea(measure.polygon.getPath());
}
if (a) {
var km = a / (1000 * 1000);
var feet = a * 10.7639104;
var yards = a * 1.19599005;
var acres = a * 0.000247105381;
var unit = " meters²";
var unit1 = " acres";
var unit2 = " km²";
var unit3 = " sq. ft.";
var unit4 = " yards²";
var area = feet.toFixed(0) + unit3;
//This is for update details in review tab
document.getElementById('estimated_area').value = parseFloat(area);
document.getElementById('field_fj0d6').value = String(area);
}
}
function rL() {
var test = measure.mvcLine.pop();
if (test) {
measure.mvcPolygon.pop();
var dot = measure.mvcMarkers.pop();
dot.setMap(null);
mC();
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDYeDBDl-8Wx98Az55EbVnpvRfSIBbwxyE&callback=initMap">
</script>
</body>
</html>
You need to bind the vertices of the polygon to the markers.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#ff5b06',
strokeOpacity: 1,
strokeWeight: 3,
fillColor: '#000000',
fillOpacity: 0.6
});
bermudaTriangle.setMap(map);
bermudaTriangle.binder = new MVCArrayBinder(bermudaTriangle.getPath());
for (var j = 0; j < bermudaTriangle.getPath().getLength(); j++) {
var mark = new google.maps.Marker({
position: bermudaTriangle.getPath().getAt(),
map: map,
draggable: true
});
mark.bindTo('position', bermudaTriangle.binder, (j).toString());
}
online example
proof of concept fiddle
code snippet:
var map;
var markers = []; // Store Marker in an Array
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 24.886,
lng: -70.268
},
mapTypeId: 'terrain'
});
// Define the LatLng coordinates for the polygon.
var triangleCoords = [{
lat: 25.774,
lng: -80.190
},
{
lat: 18.466,
lng: -66.118
},
{
lat: 32.321,
lng: -64.757
}
];
// Add Markers to Coordinates
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#ff5b06',
strokeOpacity: 1,
strokeWeight: 3,
fillColor: '#000000',
fillOpacity: 0.6
});
bermudaTriangle.setMap(map);
bermudaTriangle.binder = new MVCArrayBinder(bermudaTriangle.getPath());
for (var j = 0; j < bermudaTriangle.getPath().getLength(); j++) {
var mark = new google.maps.Marker({
position: bermudaTriangle.getPath().getAt(),
map: map,
draggable: true
});
mark.bindTo('position', bermudaTriangle.binder, (j).toString());
}
}
google.maps.event.addDomListener(window, 'load', initMap);
/*
* Use bindTo to allow dynamic drag of markers to refresh poly.
*/
function MVCArrayBinder(mvcArray) {
this.array_ = mvcArray;
}
MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function(key) {
if (!isNaN(parseInt(key))) {
return this.array_.getAt(parseInt(key));
} else {
this.array_.get(key);
}
}
MVCArrayBinder.prototype.set = function(key, val) {
if (!isNaN(parseInt(key))) {
this.array_.setAt(parseInt(key), val);
} else {
this.array_.set(key, val);
}
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
I've placed a marker(fillcolored with #333) at the center of the map that act as a radius. Initially the size of the marker was set to 151px.
Here's the scenario, if the user click the zoom out button, the size of the marker remain as is but the radius captured on the map is greater.
And if the user click the zoom in button, still the size of the marker remain the same but the radius been captured will become lesser.
The reason why I did this is I want to know if the person's current location(GPS) was inside on that specific radius that he specified using his mobile app.
My question is how can I get the current radius of the marker after the user zoom out or zoom in ? Any ideas about this problem? Thanks.
My Google Map API script:
function initGoogleMap() {
console.info('initGoogleMap');
var latitude = 10.314241194743438;
var longitude = 123.90536092883599;
var zoom = 17;
var latlng = new google.maps.LatLng(latitude, longitude);
var map_options = {
center: latlng,
zoom: zoom,
draggable: true,
zoomControl: true,
};
var map = new google.maps.Map(document.getElementById('map_canvas'), map_options);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillOpacity: 0.5,
fillColor: "#333",
strokeOpacity: 1.0,
strokeColor: '#CB0909',
strokeWeight: 0,
scale: 151 // in pixels
}
});
console.info('init zoom level: ', zoom);
marker.bindTo('position', map, 'center');
}
initGoogleMap();
See attached demo of the problem:
https://jsfiddle.net/sudogem/kkpt9t07/3/
If you know the radius of the circle in pixels you can compute the latitude and longitude of a point on the circumference using .fromLatLngToDivPixel and .fromDivPixelToLatLng, then use that to compute the radius of the circle in meters:
function computeRadius() {
if (!overlay) return;
var centerPixel = overlay.getProjection().fromLatLngToDivPixel(marker.getPosition());
var outerPoint = new google.maps.Point(centerPixel.x + 151, centerPixel.y);
var pixelLatLng = overlay.getProjection().fromDivPixelToLatLng(outerPoint);
if (!edgeMarker || !edgeMarker.setPosition) {
edgeMarker = new google.maps.Marker({
position: pixelLatLng,
map: map,
});
} else {
edgeMarker.setPosition(pixelLatLng);
}
var radius = google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(), edgeMarker.getPosition());
document.getElementById('info').innerHTML = "radius = " + (radius).toFixed(2) + " meters";
}
updated fiddle
code snippet:
function computeRadius() {
if (!overlay) return;
var centerPixel = overlay.getProjection().fromLatLngToDivPixel(marker.getPosition());
var outerPoint = new google.maps.Point(centerPixel.x + 151, centerPixel.y);
var pixelLatLng = overlay.getProjection().fromDivPixelToLatLng(outerPoint);
if (!edgeMarker || !edgeMarker.setPosition) {
edgeMarker = new google.maps.Marker({
position: pixelLatLng,
map: map,
});
} else {
edgeMarker.setPosition(pixelLatLng);
}
var radius = google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(), edgeMarker.getPosition());
document.getElementById('info').innerHTML = "radius = " + (radius).toFixed(2) + " meters";
}
var marker;
var overlay;
var edgeMarker;
var map;
function initGoogleMap() {
console.info('initGoogleMap');
var latitude = 10.314241194743438;
var longitude = 123.90536092883599;
var zoom = 17;
var latlng = new google.maps.LatLng(latitude, longitude);
var map_options = {
center: latlng,
zoom: zoom,
draggable: true,
zoomControl: true,
};
map = new google.maps.Map(document.getElementById('map_canvas'), map_options);
marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillOpacity: 0.5,
fillColor: "#333",
strokeOpacity: 1.0,
strokeColor: '#CB0909',
strokeWeight: 0,
scale: 151 // in pixels
}
});
overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
google.maps.event.addListenerOnce(map, 'idle', computeRadius);
google.maps.event.addListener(map, 'center_changed', computeRadius);
google.maps.event.addListener(map, 'zoom_changed', computeRadius);
console.info('init zoom level: ', zoom);
marker.bindTo('position', map, 'center');
}
google.maps.event.addDomListener(window, 'load', initGoogleMap);
/* Google Map */
#map_canvas {
border: 1px solid #ccc;
margin-top: 5px;
width: 100%;
height: 400px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry"></script>
<div id="map_canvas"></div>
<div id="info"></div>
This is an example from my jsonData:
"lineformap":"new google.maps.LatLng(52.25602231800669, 6.160540580749512),new google.maps.LatLng(52.25543780780041, 6.1602723598480225),new google.maps.LatLng(52.255818725438296, 6.160014867782593)"
and this is my code:
(no line appears)
When i copy the data in to the code the lines are visable on the map
Who can help me with this
var poly;
var map;
function initialize() {
var latlng = new google.maps.LatLng(52.2554, 6.1627);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var bermudaTriangle;
map = new google.maps.Map(document.getElementById("ObjectMap"), myOptions);
$.getJSON('/api/dbklineforbws', function (createbws) {
$(createbws).each(function (i, itemb) {
// Define the LatLng coordinates for the polygon's path.
var flightPlanCoordinates = [
itemb.lineformap
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
For me it's very strange usage of json file. But, to make it work I'd change json file to:
{
"lineformap": "[new google.maps.LatLng(52.25602231800669, 6.160540580749512),new google.maps.LatLng(52.25543780780041, 6.1602723598480225),new google.maps.LatLng(52.255818725438296, 6.160014867782593)]"
}
and
var flightPlanCoordinates = [
itemb.lineformap
];
to
var flightPlanCoordinates = eval(itemb.lineformap);
to get polyline.
Unfortunately I was not able to find any code / example how to draw great circle distance *between three(3) points on google maps*??
Here is the javascript for two points. How can I make it work with three points?
var geocoder;
var map;
var addresses;
var results;
var dist;
function initialize() {
geocoder = new google.maps.Geocoder();
address1 = document.getElementById("distancefrom").value;
address2 = document.getElementById("distanceto").value;
(distance(address1, address2));
}
function distance(add1, add2) {
if (!geocoder)
return 'Error, no geocoder';
addresses = new Array(2);
addresses[0] = add1;
addresses[1] = add2;
results = new Array(2);
results[0] = new Array(2);
results[1] = new Array(2);
results[0][0] = 0; results[0][1] = 0; results[1][0] = 0; results[1][1] = 0.87;
geocoded(1);
}
function geocoded(i) {
geocoder.geocode( { 'address': addresses[i] }, function(res, status) {
if (status == google.maps.GeocoderStatus.OK) {
results[i][0] = parseFloat(res[0].geometry.location.lat());
results[i][1] = parseFloat(res[0].geometry.location.lng());
i--;
if (i >= 0)
geocoded(i);
else {
var latlng1 = new google.maps.LatLng(results[0][0], results[0][1]);
var latlng2 = new google.maps.LatLng(results[1][0], results[1][1]);
dist = google.maps.geometry.spherical.computeDistanceBetween(latlng1, latlng2)/1000;
var dmi = 0.539957*dist;
document.getElementById('totaldistancemiles').value = dmi.toFixed(2);
document.getElementById('totaldistancekm').value = dist.toFixed(2);
showMap(latlng1,latlng2);
}
}
});
}
function showMap(location1,location2) {
latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,
(location1.lng()+location2.lng())/2);
faddress1 = document.getElementById("distancefrom").value;
faddress2 = document.getElementById("distanceto").value;
var mapOptions =
{
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var flightPlanCoordinates = [
location1,
location2
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: .5,
geodesic: true,
strokeWeight: 3
});
flightPath.setMap(map);
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#000000",
strokeOpacity: .5,
strokeWeight: 0
});
flightPath.setMap(map);
var igreen= 'https://dl.dropboxusercontent.com/u/85343999/igreen.gif';
var marker = new google.maps.Marker({
map: map,
icon: igreen,
position: location1
});
var latlngbounds;
latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend( location1);
latlngbounds.extend( location2);
map.fitBounds(latlngbounds);
var infowindow = new google.maps.InfoWindow();
infowindow.setContent(faddress1);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
var marker2 = new google.maps.Marker({
map: map,
icon: igreen,
position: location2
});
var infowindow2 = new google.maps.InfoWindow();
infowindow2.setContent(faddress2);
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
}
The following code uses Googles geometry library to calculate distances between points.The locations are stored in this case in an array, but can be obtained from textboxes etc. The distances are given in metres .
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
var coords = [
[35.733972, -5.881999],
[35.734077, -5.881033],
[35.736898, -5.877771],
];
function calcDistance() {
var first = new google.maps.LatLng(coords[0][0],coords[0][1]);
var second = new google.maps.LatLng(coords[1][0],coords[1][1]);
var third = new google.maps.LatLng(coords[2][0],coords[2][1]);
var distance1 = google.maps.geometry.spherical.computeDistanceBetween(first, second);
var distance2 = google.maps.geometry.spherical.computeDistanceBetween(first, third);
var distance3 = google.maps.geometry.spherical.computeDistanceBetween(second, third);
showDistance(distance1,distance2,distance3);
}
function showDistance(distance1,distance2,distance3) {
document.write("Distance1 "+distance1 + " metres <br>");
document.write("Distance2 "+distance2 + " metres <br>");
document.write("Distance3 "+distance3 + " metres <br>");
}