Remove polyline - google-maps-api-3

I have the next code which show a path using a polyline. How can I remove it?
downloadUrl("myfile.asp", function(data) {
var xml = xmlParse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
var path = [];
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
path.push(point);
}//finish loop
var polyline = new google.maps.Polyline({
path: path,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
}); //end download url
I have tried it using the next function but I m not able to make it work.
function removePath() {
polyline.setMap(null)
}

I think the problem is position of the variable "polyline".
var polyline = null;
downloadUrl("myfile.asp", function(data) {
...
polyline = new google.maps.Polyline({
path: path,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
}); //end download url
function removePath() {
polyline.setMap(null)
}

Related

How to catch if google maps infowindow if it overlays other?

I have a polyline on which i need to show each points coordinates, but the problem is that each info-window overlays other so i decided to draw only those info-windows which doesnt overlay others, but don't have any idea how to catch it...
Currently i have
window.onload = function() {
var bounds = new google.maps.LatLngBounds();
var coordinates = [];
map = new google.maps.Map(document.getElementById('map_canvas'), {mapTypeId: google.maps.MapTypeId.HYBRID});
for (i = 0, len = points.point.length; i < len; i++) {
var tmp_coor = new google.maps.LatLng(points.point[i].lat, points.point[i].lon);
coordinates.push(tmp_coor);
bounds.extend(tmp_coor);
var infowindow = new google.maps.InfoWindow({
content: points.point[i].lat + ', ' + points.point[i].lon,
maxWidth: 120
});
infowindow.setPosition(tmp_coor);
infowindow.open(map);
}
var polyline = new google.maps.Polyline({
path: coordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
editable: false
});
polyline.setMap(map);
map.fitBounds(bounds);
}
It creates
So maybe someone has any suggestions on this problem?

Google Maps API - Multiple snap to road polylines

I inserted a polyline snap to road. It works fine.
Now, I'd like to insert another separated polyline snap to road, in the same map. And it doesn't work fine. It systematically joins the end point of the first polyline to the start point of the second polyline.
Thanks for your help.
Here is my code
function initialize() {
var pos = new google.maps.LatLng(-26.431228,-69.572755);
var myOptions = {
zoom: 5,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
map.setCenter(pos);
//FIRST POLYLINE SNAP TO ROAD
ChileTrip1 = [
new google.maps.LatLng(-33.417723,-70.605018),
new google.maps.LatLng(-33.022446,-71.551688)
];
var traceChileTrip1 = new google.maps.Polyline({
path: ChileTrip1,
strokeColor: "red",
strokeOpacity: 1.0,
strokeWeight: 2
});
var service1 = new google.maps.DirectionsService(),traceChileTrip1,snap_path=[];
traceChileTrip1.setMap(map);
for(j=0;j<ChileTrip1.length-1;j++){
service1.route({origin: ChileTrip1[j],destination: ChileTrip1[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
traceChileTrip1.setPath(snap_path);
}
});
}
//SECOND POLYLINE SNAP TO ROAD
ChileTrip2 = [
new google.maps.LatLng(-29.959694,-71.30825),
new google.maps.LatLng(-32.778038,-71.181908)
];
var traceChileTrip2 = new google.maps.Polyline({
path: ChileTrip2,
strokeColor: "blue",
strokeOpacity: 1.0,
strokeWeight: 2
});
var service2 = new google.maps.DirectionsService(),traceChileTrip2,snap_path=[];
traceChileTrip2.setMap(map);
for(j=0;j<ChileTrip2.length-1;j++){
service2.route({origin: ChileTrip2[j],destination: ChileTrip2[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
traceChileTrip2.setPath(snap_path);
}
});
}
};
window.onload = function() { initialize();};
The DirectionsService is asynchronous. Either clear the snap_path array inside the callback routine before using it or create 2 separate snap_path arrays:
function initialize() {
var pos = new google.maps.LatLng(-26.431228,-69.572755);
var myOptions = {
zoom: 5,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
map.setCenter(pos);
//FIRST POLYLINE SNAP TO ROAD
ChileTrip1 = [
new google.maps.LatLng(-33.417723,-70.605018),
new google.maps.LatLng(-33.022446,-71.551688)
];
var traceChileTrip1 = new google.maps.Polyline({
path: ChileTrip1,
strokeColor: "red",
strokeOpacity: 1.0,
strokeWeight: 2
});
var service1 = new google.maps.DirectionsService(),traceChileTrip1,snap_path1=[];
traceChileTrip1.setMap(map);
for(j=0;j<ChileTrip1.length-1;j++){
service1.route({origin: ChileTrip1[j],destination: ChileTrip1[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path1 = snap_path1.concat(result.routes[0].overview_path);
traceChileTrip1.setPath(snap_path1);
} else alert("Directions request failed: "+status);
});
}
//SECOND POLYLINE SNAP TO ROAD
ChileTrip2 = [
new google.maps.LatLng(-29.959694,-71.30825),
new google.maps.LatLng(-32.778038,-71.181908)
];
var traceChileTrip2 = new google.maps.Polyline({
path: ChileTrip2,
strokeColor: "blue",
strokeOpacity: 1.0,
strokeWeight: 2
});
var service2 = new google.maps.DirectionsService(),traceChileTrip2,snap_path2=[];
traceChileTrip2.setMap(map);
for(j=0;j<ChileTrip2.length-1;j++){
service2.route({origin: ChileTrip2[j],destination: ChileTrip2[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path2 = snap_path2.concat(result.routes[0].overview_path);
traceChileTrip2.setPath(snap_path2);
} else alert("Directions request failed: "+status);
});
}
};
window.onload = function() { initialize();};
working example
Note that the overview_path is "simplified" and will not necessarily follow the road. If you need the exact route you need to process through all the legs.

Remove completely polyline

I have the next code for loading a path using a xml file, but when I try to load another path for other vehicle, it load also the last path together with the new one.
Before load the XML file again I firstly call a remove function. But it only hide the path .
Best regards.
var polyline = [];
function path() {
downloadUrl("myPath.asp?vehicle=12", function(data) {
var xml = xmlParse(data);
var markersPath = xml.documentElement.getElementsByTagName("marker");
//var path = [];
for (var i = 0; i < markersPath.length; i++) {
var lat = parseFloat(markersPath[i].getAttribute("lat"));
var lng = parseFloat(markersPath[i].getAttribute("lng"));
var pointPath = new google.maps.LatLng(lat,lng);
path.push(pointPath);
}//finish loop
polyline = new google.maps.Polyline({
path: path,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
//new polyline
polyline.setMap(map);
}); //end download url
}
function removePath() {
polyline.setMap(null);
polyline = null;
}

RouteBoxer not working

A polyline is created using the click function. I am using the RouteBoxer Utility to create a set of boxes along this polyline. I have tested the drawBoxes function with an alert box and it is working but the boxes are not showing up. I guess i'm missing something. Any tips?
(function() {
window.onload = function() {
var places = [];
var path;
var string = "";
var para = document.getElementById("para");
var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null;
//create reference to div tag in HTML file
var mapDiv = document.getElementById('map');
// option properties of map
var options = {
center: new google.maps.LatLng(-20.2796, 57.5074),
zoom : 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create map object
var map = new google.maps.Map(mapDiv, options);
// create MVC array to populate on click event
var route = new google.maps.MVCArray();
var polyline = new google.maps.Polyline({
path: route,
strokeColor: '#ff0000',
strokeOpacity: 0.6,
strokeWeight: 5
});
polyline.setMap(map);
// create click event,attach to map and populate route array
google.maps.event.addListener(map,'click', function(e) {
// create reference to polyline object
path = polyline.getPath();
// add the position clicked on map to MVC array
path.push(e.latLng);
});
$('#compute').click(function() {
routeBoxer = new RouteBoxer();
distance = parseFloat((0.1) * 1.609344);
var boxes = routeBoxer.box(polyline,distance);
drawBoxes(boxes);
});
};
})();
// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
alert('working in function');
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 3,
map: map
});
}
}
Your var map needs to be global, otherwise it is not visible from within function drawBoxes().
Move the declaration outside the function.
var map;
(function() {
window.onload = function() {
var places = [];
var path;
var string = "";
var para = document.getElementById("para");
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null;
//create reference to div tag in HTML file
var mapDiv = document.getElementById('map');
// option properties of map
var options = {
center: new google.maps.LatLng(-20.2796, 57.5074),
zoom : 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create map object -
//============== no 'var' keyword here ======================
map = new google.maps.Map(mapDiv, options);
... etc ...

direction routes - only the main streets

this is my example http://gidzior.net/map/v3_animate_marker_directions.html (i'm using placeholder in the input), thx for the GM code to geocodezip.com here
in my example i'm using Google Maps API 3, is it possible set only main streets in the direction routes ?
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var position;
var marker = null;
var polyline = null;
var poly2 = null;
var speed = 0.000005, wait = 1;
var infowindow = null;
var zoomed;
var myPano;
var panoClient;
var nextPanoId;
var timerHandle = null;
function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
//marker.myname = label;
// gmarkers.push(marker);
/*google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});*/
return marker;
}
function initialize() {
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService();
// Create a map and center it on Warszawa.
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
address = 'warszawa'
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
map.setCenter(results[0].geometry.location);
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
}
var steps = []
function calcRoute(){
if (timerHandle) { clearTimeout(timerHandle); }
if (marker) { marker.setMap(null);}
polyline.setMap(null);
poly2.setMap(null);
directionsDisplay.setMap(null);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var travelMode = google.maps.DirectionsTravelMode.DRIVING
var request = {
origin: start,
destination: end,
travelMode: travelMode
};
// Route the directions and pass the response to a
// function to create markers for each step.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation = new Object();
endLocation = new Object();
// For each route, display summary information.
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;
// marker = google.maps.Marker({map:map,position: startLocation.latlng});
marker = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
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;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
// createMarker(endLocation.latlng,"end",endLocation.address,"red");
map.setZoom(18);
startAnimation();
zoomed=false;
}
});
}
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol;
var k=0;
var stepnum=0;
var speed = "";
var lastVertex = 1;
//=============== animation functions ======================
function updatePoly(d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2.getPath().getLength() > 20) {
poly2=new google.maps.Polyline([polyline.getPath().getAt(lastVertex-1)]);
// map.addOverlay(poly2)
}
if (polyline.GetIndexAtDistance(d) < lastVertex+2) {
if (poly2.getPath().getLength()>1) {
poly2.getPath().removeAt(poly2.getPath().getLength()-1)
}
poly2.getPath().insertAt(poly2.getPath().getLength(),polyline.GetPointAtDistance(d));
} else {
poly2.getPath().insertAt(poly2.getPath().getLength(),endLocation.latlng);
}
}
function animate(d) {
// alert("animate("+d+")");
if (d>eol) {
map.panTo(endLocation.latlng);
marker.setPosition(endLocation.latlng);
return;
}
if (d>eol-1000 && zoomed!=true) {
map.setZoom(15); // or whatever value
zoomed=true;
}
var p = polyline.GetPointAtDistance(d);
map.panTo(p);
marker.setPosition(p);
updatePoly(d);
timerHandle = setTimeout("animate("+(d+step)+")", tick);
}
function startAnimation() {
eol=polyline.Distance();
map.setCenter(polyline.getPath().getAt(0));
// map.addOverlay(new google.maps.Marker(polyline.getAt(0),G_START_ICON));
// map.addOverlay(new GMarker(polyline.getVertex(polyline.getVertexCount()-1),G_END_ICON));
// marker = new google.maps.Marker({location:polyline.getPath().getAt(0)} /* ,{icon:car} */);
// map.addOverlay(marker);
poly2 = new google.maps.Polyline({path: [polyline.getPath().getAt(0)], strokeColor:"#0000FF", strokeWeight:10});
// map.addOverlay(poly2);
setTimeout("animate(50)",2000); // Allow time for the initial map display
}
No. You have options avoidHighways and avoidTolls, but there's nothing like avoidByways. This is because the service needs to get as close as possible to origin and destination and it may only be possible to use byways to get there. avoidHighways is possible because it's highly likely there is some route from A to B without using a motorway. [An exception is where a motorway connects two islands and there is no minor road route: I don't know if avoidHighways merely avoids them and the API would in fact use a highway if there is no alternative.]
The API will favour fast routes, so main streets will be preferred by default. If you were able to instruct the API to use only main streets, it is entirely possible that it would not be able to find directions between A and B.

Resources