I have a strange scenario with regards to a Polyline that is being drawn on the map. Before I post the code, I'll first demonstrate what happens when I make use of the normal direction services (Both calculates the resulting disctance the same = Total Distance: 62.734 km):
Now, when I draw the directions myself - this straight line appears out of nowhere:
Code snippet:
<script type="text/javascript">
var markers = [
{
"lat": '-26.2036247253418',
"lng": '28.0086193084717'
}
,
{
"lat": '-26.1259479522705',
"lng": '27.9742794036865'
}
,
{
"lat": '-25.8434619903564',
"lng": '28.2100086212158'
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var totalDistance = 0;
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
//var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
label: labels[labelIndex++ % labels.length],
//icon: image
});
latlngbounds.extend(marker.position);
(function (marker, data) {
// google.maps.event.addListener(marker, "click", function (e) {
// infoWindow.setContent(data.description);
// infoWindow.open(map, marker);
// });
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
setMap: map
});
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
//poly.strokeColor = '#'+Math.floor(Math.random()*16777215).toString(16);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
var myroute = directionsDisplay.directions.routes[0];
var distance = 0;
for (i = 0; i < myroute.legs.length; i++) {
distance += myroute.legs[i].distance.value;
//for each 'leg'(route between two waypoints) we get the distance and add it to the total
}
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
//console.log(result.routes[0].legs[0].distance);
}
totalDistance += distance;
document.getElementById('total').innerHTML = (totalDistance / 1000) + ' km';
}
});
}
}
}
</script>
<div id="dvMap"></div>
<div><p>Total Distance: <span id="total"></span></p></div>
Ok, so to solve the problem. Just remove the following line:
Reference: Google Documentation - Simple Polylines
And like that, the line is gone:
Aren't you also drawing a line between the first and last poly?
You should only draw lines between poly0 and poly1, poly1 and poly2 etc. but not poly100 and poly0 (if poly100 is the last one)
That would explain the straight line going from point B to A completing the shape. you don't want to complete the shape, so stop drawing. is there no function you can set to not complete the shape?
I only know of a very expensive work around and that is to trace back in reverse order from B to A along the same route. But that is probably not what you are looking for
Related
I have rendered a map with markers, which are saved as long lat values in a local xlsx file.
My aim is to automatically zoom to all markers, which are loaded via an input file button. For this I am using the fitbounds() method from googlemaps API.
Partial Example
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
var result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//create global infoWindow object
var infoWindow = new google.maps.InfoWindow();
var i, newMarker;
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
}
}
};
reader.readAsArrayBuffer(f);
}
But if I run my html file, it zooms just to one marker. I suppose that it is the first marker of the gmarkers array.
However I want to achieve following result, with the full extent of my uploaded marker:
In my main.html you can see my initMap() function and the function which is called if the document is ready. In the document ready function the handlefunction () is called.
var map;
//Change event to dropdownlist
$(document).ready(function(){
a = $('#input-id').fileinput({
'showUpload': false,
'showPreview': false,
'showCaption': false
});
a.change(handleFile);
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 48.7758459, lng: 9.1829321},
zoom: 3,
mapTypeControl: false
});
}
You have a typo in your code. Move the initialization of the bounds outside the loop.
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
should be:
bounds = new google.maps.LatLngBounds();
for (var i=0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
proof of concept fiddle
code snippet:
var result = [{
Latitude: 37.4419,
Longitude: -122.1419
}, {
Latitude: 37.44,
Longitude: -122.14
}, {
Latitude: 40.44,
Longitude: -75.14
}]
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
This is another approach for your problem within 35 lines of code.
Make sure you pass the JSON object the right way and that you declare your classes within the appropriate lexical scope.
Make sure the JSON Object returns something like this:
const coords = [
{lat: 42.4, lng: 1.55},
{lat: 43.42, lng: 2.48},
{lat: 45.43, lng: 4.9}
];
Note I have changed result to a more meaningful coords array of objects.
// Create your markers without worrying about scope and without extensive For Loops
const markers = coords.map((coord) => {
return new google.maps.Marker({
position: new google.maps.LatLng(coord.lat, coord.lng),
map: map,
animation: google.maps.Animation.DROP
});
})
// Declare your bounds outside the map method (previous for loop)
const bounds = new google.maps.LatLngBounds();
// Iterate through markers and return coords for expanded viewport
markers.forEach((loc) =>{
loc = new google.maps.LatLng(loc.position.lat(), loc.position.lng());
return bounds.extend(loc);
});
map.fitBounds(bounds);
}
I'm facing a problem with google map, the problem is,when i draw rout between markers it duplicated heres the image :
enter image description here
heres the makers:
var markers=[{"longitude":"-5.808954951287861","latitude":"35.77107409886168","deviceTime":"2017-03-29T14:02:36.000+0000"},
{"longitude":"-5.807401662705262","latitude":"35.77029143851354","deviceTime":"2017-03-29T14:05:36.000+0000"},
{"longitude":"-5.794769662196012","latitude":"35.77169804990058","deviceTime":"2017-03-29T14:08:36.000+0000"},
{"longitude":"-5.784207185242776","latitude":"35.76541442176138","deviceTime":"2017-03-29T14:11:36.000+0000"},
{"longitude":"-5.78417853735302","latitude":"35.76539666006973","deviceTime":"2017-03-29T14:14:36.000+0000"},
{"longitude":"-5.784050767764706","latitude":"35.76528034963732","deviceTime":"2017-03-29T14:15:52.000+0000"}];
heres the function :
storyboard.drawTrajet=function(markers){
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var mapOptions = {
center: new google.maps.LatLng(markers[0].latitude, markers[0].longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
alert(markers.length);
var myLatlng = new google.maps.LatLng(data.latitude, data.longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
//icon: icons['info'].icon,
label: labels[labelIndex++ % labels.length],
position: myLatlng,
map: map
//title: 'data.title'
});
//path[z].push(marker.getPosition());
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "mouseover", function (e) {
storyboard.geocodeLatLng($scope.geocoder , map, $scope.infoWindow,data.latitude,data.longitude, false,false);
//alert( $scope.MyPos);
infoWindow.setContent('<div ><i class="fa fa-calendar" aria-hidden="true"></i> '+$filter('date')(data.deviceTime, "HH:mm:ss")
+' '+'<i class="glyphicon glyphicon-bookmark" aria-hidden="true"></i>'+$scope.MyPos
+'<div>'
+'<i class="glyphicon glyphicon-map-marker" aria-hidden="true"></i>'+data.latitude+' '
+'<i class="glyphicon glyphicon-map-marker" aria-hidden="true"></i>'+data.longitude
+'</div>'
+'</div>');
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
//alert("sss");
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
//src.setMap(null);
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
// alert("sssscvvvvvvs");
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
can anyone help please to resolve this problem??
I Think you should use Waypoints for this case. please see example from this.
https://developers.google.com/maps/documentation/javascript/directions#Waypoints
I'm doing an application with google maps API that have a JSON with the marker's coordinates. Then I draw polylines between the markers. I also implemented a function with a onclick event that creates a new marker inside the polyline. This marker has to show information of the previous marker in the polyline (the one taked of the JSON, not a clicked one). But I don't know how to take the previous vertex(marker) of a selected polyline.
Code:
(function() {
window.onload = function() {
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.HYBRID,
noClear: true,
panControl: true,
scaleControl: false,
streetViewControl:false,
overviewMapControl:false,
rotateControl:false,
mapTypeControl: true,
zoomControl: false,
};
var map = new google.maps.Map(document.getElementById('map'), options);
// JSON
$.getJSON("loc.js", function(json) {
console.log(json);
});
//Marker type
var markers = [];
var arr = [];
var pinColor = "FE7569";
var pinImage = new google.maps.MarkerImage("http://labs.google.com/ridefinder/images/mm_20_red.png" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
// JSON loop
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
arr.push(latLng);
// Create markers
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: pinImage,
});
infoBox(map, marker, data);
//Polylines
var flightPath = new google.maps.Polyline({
path: json,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map:map
});
infoPoly(map, flightPath, data);
//Calculate polylines distance
google.maps.LatLng.prototype.kmTo = function(a){
var e = Math, ra = e.PI/180;
var b = this.lat() * ra, c = a.lat() * ra, d = b - c;
var g = this.lng() * ra - a.lng() * ra;
var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d/2), 2) + e.cos(b) * e.cos
(c) * e.pow(e.sin(g/2), 2)));
return f * 6378.137;
}
google.maps.Polyline.prototype.inKm = function(n){
var a = this.getPath(n), len = a.getLength(), dist = 0;
for (var i=0; i < len-1; i++) {
dist += a.getAt(i).kmTo(a.getAt(i+1));
}
return dist;
}
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
salta(data.tm);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
salta(data.tm);
});
})(marker, data);
}
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data){
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
});
}
function drawPath() {
var coords = [];
for (var i = 0; i < markers.length; i++) {
coords.push(markers[i].getPosition());
}
flightPath.setPath(coords);
}
// Fit these bounds to the map
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < arr.length; i++) {
bounds.extend(arr[i]);
}
map.fitBounds(bounds);
//dist polylines
distpoly = flightPath.inKm();
distpolyround = Math.round(distpoly);
};
})();
If I click in the blue arrow, I create a marker on that point of the polyline. I that marker it takes the values of the previous one.
You can use the geometry library .poly namespace isLocationOnEdge method to determine which segment of the polyline the clicked point (new marker) is on.
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data) {
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
// find line segment. Iterate through the polyline checking each line segment.
// isLocationOnEdge takes a google.maps.Polyline as the second argument, so make one,
// then use it for the test. The default value of 10e-9 for the tolerance didn't work,
// a tolerance of 10e-6 seems to work.
var betweenStr = "result no found";
var betweenStr = "result no found";
for (var i=0; i<flightPath.getPath().getLength()-1; i++) {
var tempPoly = new google.maps.Polyline({
path: [flightPath.getPath().getAt(i), flightPath.getPath().getAt(i+1)]
})
if (google.maps.geometry.poly.isLocationOnEdge(mk.getPosition(), tempPoly, 10e-6)) {
betweenStr = "between "+i+ " and "+(i+1);
}
}
(function(mk, betweenStr) {
google.maps.event.addListener(mk, "click", function(e) {
infowindow.setContent(betweenStr+"<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, mk);
// salta(data.tm);
});
})(mk, betweenStr);
google.maps.event.trigger(mk,'click');
});
proof of concept fiddle
code snippet:
var infowindow = new google.maps.InfoWindow();
(function() {
window.onload = function() {
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.HYBRID,
};
var map = new google.maps.Map(document.getElementById('map'), options);
//Marker type
var markers = [];
var arr = [];
var pinColor = "FE7569";
var pinImage = "http://labs.google.com/ridefinder/images/mm_20_red.png";
// JSON loop
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
arr.push(latLng);
// Create markers
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: pinImage,
});
infoBox(map, marker, data);
//Polylines
var flightPath = new google.maps.Polyline({
path: json,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
infoPoly(map, flightPath, data);
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infowindow.setContent("tm:" + data.tm + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, marker);
// salta(data.tm);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infowindow.setContent("tm:" + data.tm + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, marker);
// salta(data.tm);
});
})(marker, data);
}
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data) {
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
// find line segment. Iterate through the polyline checking each line segment.
// isLocationOnEdge takes a google.maps.Polyline as the second argument, so make one,
// then use it for the test. The default value of 10e-9 for the tolerance didn't work,
// a tolerance of 10e-6 seems to work.
var betweenStr = "result no found";
for (var i = 0; i < flightPath.getPath().getLength() - 1; i++) {
var tempPoly = new google.maps.Polyline({
path: [flightPath.getPath().getAt(i), flightPath.getPath().getAt(i + 1)]
})
if (google.maps.geometry.poly.isLocationOnEdge(mk.getPosition(), tempPoly, 10e-6)) {
betweenStr = "between " + i + " and " + (i + 1);
}
}
(function(mk, betweenStr) {
google.maps.event.addListener(mk, "click", function(e) {
infowindow.setContent(betweenStr + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, mk);
// salta(data.tm);
});
})(mk, betweenStr);
google.maps.event.trigger(mk, 'click');
});
}
function drawPath() {
var coords = [];
for (var i = 0; i < markers.length; i++) {
coords.push(markers[i].getPosition());
}
flightPath.setPath(coords);
}
// Fit these bounds to the map
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < arr.length; i++) {
bounds.extend(arr[i]);
}
map.fitBounds(bounds);
//dist polylines
distpoly = flightPath.inKm();
distpolyround = Math.round(distpoly);
};
})();
var json = [{
lat: 38.931808,
lng: -74.906606,
tm: 0
}, {
lat: 38.932442,
lng: -74.905147,
tm: 1
}, {
lat: 38.93311,
lng: -74.903473,
tm: 2
}, {
lat: 38.933777,
lng: -74.901671,
tm: 3
}, {
lat: 38.930739,
lng: -74.912528,
tm: 1000
}];
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map"></div>
INITIALIZING
When you are creating those markers in the for loop, add them to a map [Data structure] that you define (empty) before the loop. In the map markers will be stored. Their keys - concatenated lat/lng.
var initial_markers = {}; //before for loop
initial_markers[data.lat+"-"+data.lng] = marker; //after each marker initialization
Count them, so you know how many there are initial_marker_count, because you cannot get length of size of a map[data structure]
DETECTION
When you have clicked on a polyline, I don't think you can get exactly the part of polyline that is clicked, so you need to get it yourself. The steps are:
Get the coordinate of click event
Loop through the markers
Take their coordinates
Check if the clicked point on the map is on the line between those two points
If is, take the first of those two points
DETECTION PSEUDOCODE
var prev_marker;
for (var i=initial_markers; i<initial_marker_count-2; i++) {
if( isPointOnLine(initial_markers[i], initial_markers[i+1], clicked_point) {
prev_marker = initial_markers[i];
break;
}
}
The only reason I am saying that this is pseudocode, is because I don't know hor to find if point is on the line between two points in Google maps. And you should write that isPointOnLine() functions. Apart from that - the idea is given. Hope You appreciate it.
I am playing around with the Google Maps API v3 for a project I am building.The premise is the user can draw a route on the map however at any point can clear it and start again. The issue I am having is restarting the polyline after the map has been cleared. Whilst the markers appear the polyline does not.
I have discovered that the line poly.setMap(null); only hides the polyline that is draw and doesn't clear it therefore it is understandable why the line doesn't show. However on finding this out I now need to know how to clear it and how it can be restarted.
The code is below:
var poly;
var map, path = new google.maps.MVCArray(),
service = new google.maps.DirectionsService(), poly;
var removepolyline;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
var count = 0;
var countname = 0;
var latitude_start;
var longitude_start;
function initialize() {
var mapOptions = {
zoom: 16,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
geocoder = new google.maps.Geocoder();
///Geolocation
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
///Place fallback loop
}
///Allows the polyline to follow the road
poly = new google.maps.Polyline({ map: map });
google.maps.event.addListener(map, "click", function(evt) {
if (path.getLength() === 0) {
//Enters on first click
path.push(evt.latLng);
poly.setPath(path);
} else {
//Enters on second click
service.route({
origin: path.getAt(path.getLength() - 1),
destination: evt.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length;
i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
var latitude_longitude = evt.latLng;
var latitude = evt.latLng.lat();
var longitude = evt.latLng.lng();
//alert(latitude_longitude);
//alert(latitude);
// alert(longitude);
///Saves the first click location
if(count === 0){
var latitude_start = evt.latLng.lat();
var longitude_start = evt.latLng.lng();
var firstlat = latitude_start;
var firstlng = longitude_start;
/////Trying to calculate distance
var origin1 = new google.maps.LatLng(firstlat, firstlng);///1st click - never changes
document.getElementById("origin1").value = origin1;
document.getElementById("startpoint").value = origin1;
////Calculate distance
var destinationA = new google.maps.LatLng(latitude, longitude); ///Most recent click
document.getElementById("destination").value = destinationA; ////Stores Destination
var origin1 = document.getElementsByName('origin1')[0].value ////Retrieves value from text box
count ++;
}else{
var origin1 = document.getElementsByName('destination')[0].value ////Retrieves value from text box
////Calculate distance
var destinationA = new google.maps.LatLng(latitude, longitude); ///Most recent click
document.getElementById("destination").value = destinationA; ////Stores Destination
}
////Calculate distance
var servicetime = new google.maps.DistanceMatrixService();
servicetime.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
}, callback);
});
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
///Enters the if it is the first loop round/first click
if(countname === 0){
document.getElementById("startpointname").value = origins;
countname ++;
}
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
//deleteOverlays(); ////
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
//addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += start + ' to ' + destinations[j]
+ ': ' + miles + ' miles in '
+ overalltime + ' minutes <br>';
}
}
}
}
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addLatLng);
}////Function initialize ends here
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
/**
* Handles click events on a map, and adds a new point to the Polyline.
* #param {google.maps.MouseEvent} event
*/
function addLatLng(event) {
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
markersArray.push(marker);
}///Function addLatLng ends here
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
}
function clearall() {
poly.setMap(null);//Just hiding them
clearMarkers();
markersArray = [];
///////////////////CLEAR ALL VALUES IN HERE i.e. miles, time etc and CLEAR MARKERS
restartpolyline();
}
//////////////////////////////////////////WHEN CLEARED THE CODE NEEDS INTITALISING AGAIN
function restartpolyline(){
//alert("Restart");
}
//https://developers.google.com/maps/documentation/javascript/reference#Polyline
google.maps.event.addDomListener(window, 'load', initialize);
To view what currently happens view the following link: http://kitlocker.com/sotest.php
Instead of poly.setMap(null); call path.clear();
Polyline is just an array of LatLng objects, not individual Polylines, which you can then loop over to remove them all.
You can make it invisible or remove it from the map by looping it like this:
var size = poly.length;
for (i=0; i<size; i++)
{
poly[i].setMap(null);
}
I am developing an app using phone gap which have the functionality to draw route between two location on Google map but it some times draws the route on map and hides some times. My code is below:
var gmarkers = [];
function drawRoute(addressCurrent, addessDestination) {
console.log("Inside draw root");
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(lat, longi)
};
map = new google.maps.Map(document.getElementById('mapDirection'), mapOptions);
var directionsService = new google.maps.DirectionsService();
var request = {
origin: addressCurrent,
destination: addessDestination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#0000ff',
strokeWeight: 3
});
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation = new Object();
endLocation = new Object();
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
createMarker(legs[i].start_location, "start", legs[i].start_address);
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
var dist_dur = "";
if (steps[j].distance && steps[j].distance.text) dist_dur += " " + steps[j].distance.text;
if (steps[j].duration && steps[j].duration.text) dist_dur += " " + steps[j].duration.text;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
console.log("Outside draw root");
createMarker(endLocation.latlng, "end", endLocation.address);
// == create the initial sidebar ==
}
});
}
function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var iconImage;
if (label == "start") {
iconImage = new google.maps.MarkerImage("images/start.png",
// This marker is 30 pixels wide by 55 pixels tall.
new google.maps.Size(30, 55),
// The origin for this image is 0,0.
new google.maps.Point(0, 0),
// The anchor for this image is at 16,47.
new google.maps.Point(16, 47));
} else {
iconImage = new google.maps.MarkerImage("images/marker.png",
// This marker is 30 pixels wide by 55 pixels tall.
new google.maps.Size(30, 55),
// The origin for this image is 0,0.
new google.maps.Point(0, 0),
// The anchor for this image is at 16,47.
new google.maps.Point(16, 47));
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: iconImage,
title: label,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
marker.myname = label;
gmarkers.push(marker);
}
This code is working well with ripple emulator but the problem with when its running on Android device