Google Map Route Arrow Line - google-maps

I currently have these codes to load GPX File into Google Maps
function loadGPXFileIntoGoogleMap(map, filename) {
$.ajax({url: filename,
dataType: 'xml',
success: function(data) {
var parser = new GPXParser(data, map);
parser.setTrackColour('#ff0000'); // Set the track line colour
parser.setTrackWidth(5); // Set the track line width
parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points
parser.centerAndZoom(data);
parser.addTrackpointsToMap(); // Add the trackpoints
parser.addWaypointsToMap(); // Add the waypoints
}
});
}
$(document).ready(function() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
loadGPXFileIntoGoogleMap(map, '" . base_url('gps/ajax/request/trace') . "');
});
Everything is good but I want to replace it with arrow lines instead of straight line. Is it possible? If yes, please help me to do it.

In order to add arrows to the polylines created by the GPXParser, you need to modify that library to give access to the polylines, see the two lines and the function added to that library below. Then get the polylines and add the arrows to them as below.
working example (based off the example in the gpxviewer documentation referenced above)
Changes to the code from the example in the documentation:
function loadGPXFileIntoGoogleMap(map, filename) {
$.ajax({url: filename,
dataType: "xml",
success: function(data) {
var parser = new GPXParser(data, map);
parser.setTrackColour("#ff0000"); // Set the track line colour
parser.setTrackWidth(5); // Set the track line width
parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points
parser.centerAndZoom(data);
parser.addTrackpointsToMap(); // Add the trackpoints
// ******************** added *******************************
var polylines = parser.getPolylines();
// documentation on pre-defined symbols and repeated symbols:
// https://developers.google.com/maps/documentation/javascript/symbols
// Define a symbol using a predefined path (an arrow)
// supplied by the Google Maps JavaScript API.
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
strokeColor: '#00FF00',
strokeOpacity: 1.0
};
for (var i=0; i<polylines.length; i++) {
polylines[i].setOptions({
icons: [{
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor:'#0000ff',
fillColor:'#0000ff',
fillOpacity:1,
scale: 3
},
repeat:'100px'
}]
});
}
// *****************************end added**********************
parser.addWaypointsToMap(); // Add the waypoints
}
});
}
Changes to the loadgpx.js library:
function GPXParser(xmlDoc, map) {
this.xmlDoc = xmlDoc;
this.map = map;
this.trackcolour = "#ff00ff"; // red
this.trackwidth = 5;
this.mintrackpointdelta = 0.0001
this.polylines = []; // **added**
}
// return a reference to the array of polylines **added function**
GPXParser.prototype.getPolylines = function() {
return this.polylines;
}
GPXParser.prototype.addTrackSegmentToMap = function(trackSegment, colour,
width) {
var trackpoints = trackSegment.getElementsByTagName("trkpt");
if(trackpoints.length == 0) {
return;
}
var pointarray = [];
// process first point
var lastlon = parseFloat(trackpoints[0].getAttribute("lon"));
var lastlat = parseFloat(trackpoints[0].getAttribute("lat"));
var latlng = new google.maps.LatLng(lastlat,lastlon);
pointarray.push(latlng);
for(var i = 1; i < trackpoints.length; i++) {
var lon = parseFloat(trackpoints[i].getAttribute("lon"));
var lat = parseFloat(trackpoints[i].getAttribute("lat"));
// Verify that this is far enough away from the last point to be used.
var latdiff = lat - lastlat;
var londiff = lon - lastlon;
if(Math.sqrt(latdiff*latdiff + londiff*londiff)
> this.mintrackpointdelta) {
lastlon = lon;
lastlat = lat;
latlng = new google.maps.LatLng(lat,lon);
pointarray.push(latlng);
}
}
var polyline = new google.maps.Polyline({
path: pointarray,
strokeColor: colour,
strokeWeight: width,
map: this.map
});
this.polylines.push(polyline); // **added
}

Related

How to get coordinates in polyline using google map?

I tried to create a polyline in google Maps. It's created and polyline also working fine. but I need when to click polyline to get coordinates. My Scenario(I have three markers in google map.so, three markers used to connect the polyline markerA connect to markerB connect to markerC. when I click polyline in between markerA and makrerB. I need that two markers latitude and longitude). How to achieve this scenario.
My Code
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var goldenGatePosition = [{lat: 11.0168,lng: 76.9558},{lat: 11.6643,lng: 78.1460},{lat:11.2189,lng:78.1674}];
for(let i=0;i<goldenGatePosition.length;i++){
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
}
var flightPath = new google.maps.Polyline({
path:goldenGatePosition,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
flightPath.setMap(map);
var infowindow = new google.maps.InfoWindow();
var codeStr=''
google.maps.event.addListener(flightPath, 'click', function(event) {
infowindow.setContent("content");
// var pathArr = flightPath.getPath()
// for (var i = 0; i < pathArr.length; i++){
// codeStr = '{lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ;
// console.log(codeStr)
// };
console.log(event.latLng)
var length = this.getLength();
var mid = Math.round( length / 2 );
var pos = this.getAt( mid );
console.log(pos)
// infowindow.position = event.latLng;
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCHmYOxkvd4u3rbHqalUSlGOa-b173lygA&callback=myMap"></script>
</body>
</html>
Google Map
Simplest way:
include the google maps geometry library.
use the poly namespace isLocationOnEdge method to detect which segment of the polyline the click was on. Output the two end coordinates of that segment.
isLocationOnEdge(point, poly[, tolerance])
Parameters:
point: LatLng
poly: Polygon|Polyline
tolerance: number optional
Return Value: boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline,10e-3)) {
// output the segment number and endpoints in the InfoWindow
var content = "segment "+i+"<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
proof of concept fiddle
code snippet:
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#googleMap {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<h1>My First Google Map</h1>
<div id="googleMap"></div>
<script>
function myMap() {
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var goldenGatePosition = [{
lat: 11.0168,
lng: 76.9558
}, {
lat: 11.6643,
lng: 78.1460
}, {
lat: 11.2189,
lng: 78.1674
}];
var bounds = new google.maps.LatLngBounds();
for (let i = 0; i < goldenGatePosition.length; i++) {
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
bounds.extend(goldenGatePosition[i]);
}
var flightPath = new google.maps.Polyline({
path: goldenGatePosition,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2
});
flightPath.setMap(map);
map.fitBounds(bounds);
var infowindow = new google.maps.InfoWindow();
var codeStr = ''
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {
// output the segment number and endpoints in the InfoWindow
var content = "segment " + i + "<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=myMap"></script>

Algolia search, displaying all results even when radius set

So I want to search by lat and lng within 5km radius, despite limiting hits per page to 10, it is still displaying all markers on map and there are 96, why isn't this working properly?
var APPLICATION_ID = '**';
var SEARCH_ONLY_API_KEY = '**';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 10 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
algoliaHelper.setQueryParameter('aroundLatLng', '53.552472, -2.807663');
algoliaHelper.setQueryParameter('aroundRadius', 5000);
algoliaHelper.search();
// Map initialization
var markers = [];
//alert("heelo");
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
label: hit.slug,
animation: google.maps.Animation.DROP
});
markers.push(marker);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
});
How a very weird reason if I delete:
algoliaHelper.setQueryParameter('aroundLatLng', '53.552472, -2.807663');
algoliaHelper.setQueryParameter('aroundRadius', 5000);
algoliaHelper.search();
It still brings back all records, does anyone have a clue why is this happening?

Dynamic Load of Heatmap Data based on Map Bounds, Performance Issue

I have implemented a simple page that uses a listener to determine when a google maps bounds have changed because of zoom or pan. I am dynamically loading json data for a weighted heatmap summarized by the area visible in the map. It is working all except for the fact that I am not properly clearing the previous data from the heatmap on each call to the listener. Performance begins to degrade after the 4th or 5th call to fetch new data. I tried setting heatmap to null. What else is needed to maintain performance?
var map, heatmap;
var heatMapData = [];
function initMap() {
var uluru = { lat: 32.673363, lng: -97.399290 };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: uluru
});
google.maps.event.addListener(map, "bounds_changed", function () {
heatmap = null;
var bounds = map.getBounds();
//TODO: implement async request
var Httpreq = new XMLHttpRequest(); // a new request
var boxRequest = 'HeatMapData?lmin=' + bounds.f.f + '&lmax=' + bounds.f.b + '&lnmin=' + bounds.b.b + '&lnmax=' + bounds.b.f;
Httpreq.open("GET", boxRequest, false);
Httpreq.setRequestHeader("Content-type", "application/json")
var heatMapJSON = Httpreq.responseText;
heatMapData = [];
var parsedJSON = JSON.parse(heatMapJSON);
for (var i = 0; i < parsedJSON.length; i++) {
heatMapData.push({ location: new google.maps.LatLng(parsedJSON[i].Lat, parsedJSON[i].Lon), weight: parsedJSON[i].weight })
};
console.info('map points: ' + parsedJSON.length.toString());
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatMapData,
map : map
});
});
if (heatmap != null) {
heatmap.setMap(null);
};

Fire event after polygon is loaded

After searching the whole day, I didn't find the answer.
So the problem is:
I have a Google Map on which the user can draw. After this, the user can save it on the server. It works fine. Here is the drawing code:
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
var all_overlays = [];
var coordinates;
var polygon;
var globalGoogleSelectedColor;
var globalGooglePinWidth;
var map;
coordObj = new Object();
function clearSelection()
{
if (selectedShape)
{
deleteAllLastShape();
selectedShape.setEditable(false);
selectedShape = null;
deleteObjectContent(coordObj);
}
}
function setSelection(shape)
{
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteAllShape()
{
console.log("deleteAllShape");
deleteObjectContent(coordObj);
for (var i=0; i < all_overlays.length; i++)
{
all_overlays[i].overlay.setMap(null);
}
all_overlays = [];
}
function deleteAllLastShape()
{
var myLenth = all_overlays.length;
if(myLenth > 1)
{
all_overlays[0].overlay.setMap(null);
all_overlays = _.rest(all_overlays);
}
}
function deleteSelectedShape()
{
if (selectedShape)
{
selectedShape.setMap(null);
deleteObjectContent(coordObj);
}
}
function selectColor(color)
{
selectedColor = color;
globalGoogleSelectedColor = selectedColor;
globalGooglePinWidth = 2; //only for Database
for (var i = 0; i < colors.length; ++i)
{
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color)
{
if (selectedShape)
{
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE)
{
selectedShape.set('strokeColor', color);
}
else
{
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color)
{
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette()
{
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i)
{
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initializeAreas()
{
map = new google.maps.Map(document.getElementById('mapBaugebieteDiv'),
{
zoom: 15,
center: new google.maps.LatLng(48.758961357888516,8.240861892700195),
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DEFAULT,
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.HYBRID
]},
disableDefaultUI: false,
zoomControl: true,
scaleControl: true,
mapTypeControl: true,
streetViewControl: true,
rotateControl: true
});
var polyOptions =
{
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager(
{
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
// google.maps.drawing.OverlayType.MARKER,
// google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.POLYLINE,
// google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON
]
},
markerOptions:
{
draggable: true
},
polylineOptions:
{
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e)
{
// Push the overlay onto an array (all_overlays):
all_overlays.push(e);
deleteAllLastShape();
if (e.type != google.maps.drawing.OverlayType.MARKER)
{
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function()
{
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
google.maps.event.addDomListener(document.getElementById('delete-all-button'), 'click', deleteAllShape);
///////////////////////////////////////
// Polylgon
///////////////////////////////////////
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon)
{
var shapeType = 'polygon';
google.maps.event.addListener(polygon.getPath(), 'insert_at', function()
{
// New point
coordinates = (polygon.getPath().getArray());
showObjectContent(coordinates);
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon.getPath(), 'remove_at', function()
{
// Point was removed
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon.getPath(), 'set_at', function()
{
// Point was moved
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon, 'dragend', function()
{
// Polygon was dragged
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
///////////////////////////////////////
// Polyline
///////////////////////////////////////
google.maps.event.addListener(drawingManager, 'polylinecomplete', function (polygon)
{
var shapeType = 'polyline';
google.maps.event.addListener(polygon.getPath(), 'insert_at', function()
{
// New point
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon.getPath(), 'remove_at', function()
{
// Point was removed
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon.getPath(), 'set_at', function()
{
// Point was moved
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon, 'dragend', function()
{
// Polygon was dragged
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initializeAreas);
But the big problem is, after reloading the lat/lng from the server and drawing it on the map, the event listener does not know about the new polygon:
function fillBuildingForm(getData)
{
var coord = getData['buildings']; // coordinates from the server
if(typeof coord[0] !== 'undefined')
{
var shapeType = coord[0]['shapeType'];
var color = coord[0]['color'];
var strokeOpacity = coord[0]['opacity'];
var strokeWeight = coord[0]['linewidth'];
var numberOfCoord = getObjectSize(coord);
var flightPlanCoordinates = new Array();
for (var i = 0; i < numberOfCoord; i++)
{
thisCoord = new Object();
thisCoord['lat']=parseFloat(coord[i]['lat']);
thisCoord['lng']=parseFloat(coord[i]['lng']);
flightPlanCoordinates.push(thisCoord);
};
var bermudaTriangle = new google.maps.Polygon(
{
paths: flightPlanCoordinates,
strokeColor: color,
strokeOpacity: strokeOpacity,
strokeWeight: strokeWeight,
fillColor: color,
fillOpacity: 0.35,
// bounds: flightPlanCoordinates,
editable: true,
draggable: true
});
bermudaTriangle.setMap(map); //now its drawing at the map
}
}
You can see, until now, it works perfectly:
But the user can change the polygon and want to save the new changed polygon on the server. The listener:
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon)
Does not recognize that the polygon has been drawn. And therefore the listener doesn't recognize when the user changes the polygon.
So the coordinates are not present in all_overlays[i].
The listener only recognizes when a polygon is drawn manually, but not in the way like the above, when it is drawn automatically.
The question: How can I send the automatically drawn polygon coordinates to the "map" object? Alternatively, how can I fire an event to "polygoncomplete", so it will recognize the new polygon?
The other idea I had: Trigger a mouse click event at the map with the coordinates, so the listener must recognize that the map has changed. But unfortunately this didn't work.
Has anybody any idea how to solve this issue?
There are not many possibilities as an event "polygon_load _complete" is not available. One suggestion is to exploit the fact that to operate on a polygon you must click it.
If you need to manage the situation when a polygon is loaded from server and the user change the shape/coordinates. you can add listener on click to every polygon during the loading phase ..
for each polygon in loading phase..
var aPoly = new google.maps.Polygon({
paths:myPaths,
.......
});
google.maps.event.addListener(aPoly, 'click', function (event) {
console.log('This polygon contain : ' + this.paths + ' coords point ');
});
In this way you can intecept the click on polygon for manage your need
your idea was a good intention, but not the end of the solution. But thank you for your hint. Because of your answer I was able finding a way.
Generally we should think, the object bermudaTriangle should have the property "paths". But it doesn't work like this way.
For getting the coordinates of the loaded Poly (loaded from server) there is a google-map function like "getPath()" or"getPaths()". It seems, that both methods are working.
Please note, I've changed the name from 'bermudaTriangle' to 'globalLoadedPoly'.
So the solution is in combination with the above code now additional:
Creating a global var:
var globalLoadedPoly;
(global is not necessary, but I did it this way for further actions)
Getting the path by function for the listeners:
var thisPolyPath = globalLoadedPoly.getPath();
Listening to events, when the loaded poly has changed:
google.maps.event.addListener(thisPolyPath, 'set_at', thisPolyHasChanged);
google.maps.event.addListener(thisPolyPath, 'insert_at', thisPolyHasChanged);
4.In the function, thisPolyHasChanged(), setting the loaded poly as the actual selection, by using the function setSelection(shape). And getting the coordinates by calling the function getCoordinatesOfLoadedPolygon
function thisPolyHasChanged()
{
// Setting the loaded poly as the new selection
// Yes, it's global, so therefore not necessary to be sent
// but like this way, it's more readable
setSelection(globalLoadedPoly);
// If you want to get the coordinates for saving
// Calling the function getCoordinatesOfLoadedPolygon
// For being more readable I send the global Object - yes, it's not necessary
coordObj = getCoordinatesOfLoadedPolygon(globalLoadedPoly,'polygon');
// do something with coordObj
// ...
}
function setSelection(shape)
{
// clearSelection is in the code I postet as the question
clearSelection();
selectedShape = shape; // setting the loaded poly as the actual poly
shape.setEditable(true); // making the loaded poly editable
selectColor(shape.get('fillColor') || shape.get('strokeColor')); //setting the color
}
function getCoordinatesOfLoadedPolygon(getPolygon,shapeType)
{
// getLength is also a google-maps function / method
var objSize = getPolygon.getPath().getLength();
for (var i = 0; i < objSize; i++)
{
// getArray is a google-maps function / method too
var thisLat = getPolygon.getPath().getArray()[i].lat();
var thisLng = getPolygon.getPath().getArray()[i].lng();
coordObj[i]=new Object();
coordObj[i]['lat']=thisLat;
coordObj[i]['lng']=thisLng;
coordObj[i]['shapeType']=shapeType;
};
return coordObj;
}
At last, if you iterate the object "coordObj" and make a console.log in firebug, it looks like this way:
0 Object { lat=51.25572693191116, lng=9.136230200529099, shapeType="polygon"}
1 Object { lat=51.80250070611026, lng=13.069335669279099, shapeType="polygon"}
2 Object { lat=49.958995050387585, lng=10.476562231779099, shapeType="polygon"}
Conclusion:
If you want to get the coordinates or other properties of a google-maps object, use the proprietary google-maps functions / methods:
// For getting the coordinates you are generally working with:
yourMapObject.getPath();
//or
yourMapObject.getPaths();
// Getting especially the latitude:
var latitude = yourMapObject.getPath().getArray()[i].lat();
// Getting especially the longitude:
var longitude = yourMapObject.getPath().getArray()[i].lng();
// Getting the number of coordinates
yourMapObject.getPath().getLength();
Don't forget to iterate over the whole object, to get all coordinates.
The solution-code could be really optimized. For being more readable, I wrote it in small steps.
I hope, I'm able helping anybody with this solution.

Google Maps V3 - waypoints + infowindow with random text

I'm using this example to set up a route with more then 8 markers.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Directions Waypoints</title>
<style>
#map{
width: 100%;
height: 450px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
jQuery(function() {
var stops = [
{"Geometry":{"Latitude":52.1615470947258,"Longitude":20.80514430999756}},
{"Geometry":{"Latitude":52.15991486090931,"Longitude":20.804049968719482}},
{"Geometry":{"Latitude":52.15772967999426,"Longitude":20.805788040161133}},
{"Geometry":{"Latitude":52.15586034371232,"Longitude":20.80460786819458}},
{"Geometry":{"Latitude":52.15923693975469,"Longitude":20.80113172531128}},
{"Geometry":{"Latitude":52.159849043774074, "Longitude":20.791990756988525}},
{"Geometry":{"Latitude":52.15986220720892,"Longitude":20.790467262268066}},
{"Geometry":{"Latitude":52.16202095784738,"Longitude":20.7806396484375}},
{"Geometry":{"Latitude":52.16088894313116,"Longitude":20.77737808227539}},
{"Geometry":{"Latitude":52.15255590234335,"Longitude":20.784244537353516}},
{"Geometry":{"Latitude":52.14747369312591,"Longitude":20.791218280792236}},
{"Geometry":{"Latitude":52.14963304460396,"Longitude":20.79387903213501}}
] ;
var map = new window.google.maps.Map(document.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer();
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);
if (stops.length > 1)
window.tour.calcRoute(directionsService, directionsDisplay);
});
function Tour_startUp(stops) {
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom: 13,
center: new window.google.maps.LatLng(51.507937, -0.076188), // default to London
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.Geometry.Latitude, val.Geometry.Longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (directionsService, directionsDisplay) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.Longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
}
}
});
})(k);
}
}
};
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
It works like a charm but I have problem to setup an infowindow for each waypoint. I would like to leave markers names like A , B ,C or generate it in otherway but to keep A,B,C or 1,2,3 pattern and I want to add infowindow to each marker which contains title text and link.
I was trying to find any info or examples but nothing works. Maybe someone have and idea how to easily add infowindow to this code.
Here is an example that draws the directions from scratch with custom markers and infowindows:
Example
If you use the suppressInfoWindows option on the DirectionsRenderer, you can just use the part of it that creates the markers and their associated infowindows.
Working example based on your code
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Directions Waypoints</title>
<style>
#map{
width: 100%;
height: 450px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
jQuery(function() {
var stops = [
{"Geometry":{"Latitude":52.1615470947258,"Longitude":20.80514430999756}},
{"Geometry":{"Latitude":52.15991486090931,"Longitude":20.804049968719482}},
{"Geometry":{"Latitude":52.15772967999426,"Longitude":20.805788040161133}},
{"Geometry":{"Latitude":52.15586034371232,"Longitude":20.80460786819458}},
{"Geometry":{"Latitude":52.15923693975469,"Longitude":20.80113172531128}},
{"Geometry":{"Latitude":52.159849043774074, "Longitude":20.791990756988525}},
{"Geometry":{"Latitude":52.15986220720892,"Longitude":20.790467262268066}},
{"Geometry":{"Latitude":52.16202095784738,"Longitude":20.7806396484375}},
{"Geometry":{"Latitude":52.16088894313116,"Longitude":20.77737808227539}},
{"Geometry":{"Latitude":52.15255590234335,"Longitude":20.784244537353516}},
{"Geometry":{"Latitude":52.14747369312591,"Longitude":20.791218280792236}},
{"Geometry":{"Latitude":52.14963304460396,"Longitude":20.79387903213501}}
] ;
var map = new window.google.maps.Map(document.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer({suppressMarkers: true});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);
if (stops.length > 1)
window.tour.calcRoute(directionsService, directionsDisplay);
});
function Tour_startUp(stops) {
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom: 13,
center: new window.google.maps.LatLng(51.507937, -0.076188), // default to London
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.Geometry.Latitude, val.Geometry.Longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (directionsService, directionsDisplay) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.Longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
// alert(legs.length);
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);
}
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,"marker"+i,"some text for the "+i+"marker<br>"+legs[legs.length-1].end_address,markerletter);
}
}
});
})(k);
}
}
};
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
function getMarkerImage(iconStr) {
if ((typeof(iconStr)=="undefined") || (iconStr==null)) {
iconStr = "red";
}
if (!icons[iconStr]) {
icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/marker"+ iconStr +".png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
}
return icons[iconStr];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconImage = new google.maps.MarkerImage('mapIcons/marker_red.png',
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function createMarker(map, latlng, label, html, color) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: iconShadow,
icon: getMarkerImage(color),
shape: iconShape,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>