Google Maps Api - drawing routes from an array of points - google-maps

I would like to connect 8 points on google map so that they shared line (road). I would like to click on the point cloud showed up with a description that point. The goal is to show the route the car point to point.
I have script to make map with points but I don't know how connect markers.
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
var flightPath = responseArray.map(function (item) {
return new google.maps.LatLng(item.latitude, item.longitude);
});
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(12);
google.maps.event.removeListener(listener);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);

to connect your markers with a google.maps.Polyline (as it looks like you are trying to do).
create an empty array: var flightPlanCoordinates = [];
push the coordinates of the markers (google.maps.LatLng objects) into the array of coordinates you use for the polyline: flightPlanCoordinates.push(marker.getPosition());
set the map option of the polyline: map:map (in the PolylineOptions object).
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
working fiddle
working code snippet:
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var infowindow = new google.maps.InfoWindow();
var flightPlanCoordinates = [];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
flightPlanCoordinates.push(marker.getPosition());
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
to connect the points using the directions service (from the example you reference)
create an empty array: var flightPlanCoordinates = [];
push the coordinates of the markers (google.maps.LatLng objects) into the array of coordinates you use for the polyline: flightPlanCoordinates.push(marker.getPosition());
use that array to populate the start, end, and waypts arguments into the calcRoute function:
var start = flightPlanCoordinates[0];
var end = flightPlanCoordinates[flightPlanCoordinates.length - 1];
var waypts = [];
for (var i = 1; i < flightPlanCoordinates.length - 1; i++) {
waypts.push({
location: flightPlanCoordinates[i],
stopover: true
});
}
calcRoute(start, end, waypts);
change the calcRoute function to use those arguments:
function calcRoute(start, end, waypts) {
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
working fiddle
working code snippet:
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
directionsDisplay.setMap(map);
var infowindow = new google.maps.InfoWindow();
var flightPlanCoordinates = [];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
flightPlanCoordinates.push(marker.getPosition());
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
// directions service configuration
var start = flightPlanCoordinates[0];
var end = flightPlanCoordinates[flightPlanCoordinates.length - 1];
var waypts = [];
for (var i = 1; i < flightPlanCoordinates.length - 1; i++) {
waypts.push({
location: flightPlanCoordinates[i],
stopover: true
});
}
calcRoute(start, end, waypts);
}
}
function calcRoute(start, end, waypts) {
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
<div id="directions_panel"></div>

Related

How to draw line between two points in JavaScript - Google Maps Api Route

I have two points on the map, I was able to take the distance using the API, now I need to draw a line between the points so that the user sees all the way. I read that you need to use the polyline, but I unfortunately can not. I take the user's GPS coordinates as point A - and on the map, in the drag event I take the coordinates of point B. You can see an example on the following page: https://tojweb.tj/abb.php
Can you help?
I read that you need to use the polyline, but I unfortunately can not.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
function showPosition(position) {
document.getElementById('mypos_lat').value=position.coords.latitude;
document.getElementById('mypos_lon').value=position.coords.longitude;
//alert("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude);
}
var darection = new google.maps.DirectionsRenderer;
function initialize() {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(38.583958, 68.780528),
mapTypeId: google.maps.MapTypeId.ROADMAP,
gestureHandling: "greedy",
fullscreenControl: false,
disableDefaultUI: true,
zoomControl: true,
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
darection.setMap(map);
google.maps.event.addListener(map, 'dragend', function() {
var centeral = map.getCenter();
//alert(centeral);
var names = centeral.toString();
var names =names.substr(1);
names = names.substring(0, names.length - 1);
console.log(names);
var re = /\s*,\s*/;
var nameList = names.split(re);
document.getElementById('bpos_lat').value=nameList[0];
document.getElementById('bpos_lon').value=nameList[1];
source_a = document.getElementById("mypos_lat").value;
source_b = document.getElementById("mypos_lon").value;
source_d = document.getElementById("bpos_lat").value;
source_e = document.getElementById("bpos_lon").value;
var darection = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//darection.setPanel(document.getElementById('panallocation'));
source = source_a + "," + source_b;
destination = source_d + "," + source_e;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
//Показ алтернативных дорог
provideRouteAlternatives: true
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
darection.setDirections(response);
}
});
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
distancefinel = distance.split(" ");
//start_addressfinel = start_address.split(" ");
// $('#distance').val(distancefinel[0]);
console.log(distancefinel[0]);
document.getElementById("distancesa").value = distancefinel[0];
////////// IN THIS STATE I WANT DRAW LINE ///////////////////
} else {
alert("Unable to find the distance between selected locations");
}
});
}
);
$('<div/>').addClass('centerMarker').appendTo(map.getDiv())
//do something onclick
.click(function(){
var that=$(this);
if(!that.data('win')){
that.data('win',new google.maps.InfoWindow({content:'this is the center'}));
that.data('win').bindTo('position',map,'center');
}
that.data('win').open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
You can use the Directions Service of Google Maps JavaScript API to get the directions between 2 points and pass the DirectionsResult to the DirectionsRenderer, which can automatically handle the display in the map.
Here is the code I made which handles the use-case (Geolocating Point A, Draggable Marker B, then having a route between 2 points) from your description. You can also check it here.
Hope this helps!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
#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>
<script>
var map, infoWindow, markerA, markerB, drag_pos;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
markerA = new google.maps.Marker({
map: map
});
markerB = new google.maps.Marker({
map: map
});
infoWindow = new google.maps.InfoWindow;
var directionsService = new google.maps.DirectionsService();
var directionsRenderer1 = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true
});
var directionsRenderer2 = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
polylineOptions: {
strokeColor: "gray"
}
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
map.setZoom(15);
//Put markers on the place
infoWindow.setContent('Your Location');
markerA.setPosition(pos);
markerA.setVisible(true);
markerA.setLabel('A');
markerA.addListener('click', function() {
infoWindow.open(map, markerA);
});
//Get new lat long to put marker B 500m above Marker A
var earth = 6378.137, //radius of the earth in kilometer
pi = Math.PI,
m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree
var new_latitude = pos.lat + (500 * m);
var new_pos = {
lat: new_latitude,
lng: position.coords.longitude
};
markerB.setPosition(new_pos, );
markerB.setVisible(true);
markerB.setLabel('B');
markerB.setDraggable(true);
//Everytime MarkerB is drag Directions Service is use to get all the route
google.maps.event.addListener(markerB, 'dragend', function(evt) {
var drag_pos1 = {
lat: evt.latLng.lat(),
lng: evt.latLng.lng()
};
directionsService.route({
origin: pos,
destination: drag_pos1,
travelMode: 'DRIVING',
provideRouteAlternatives: true
},
function(response, status) {
if (status === 'OK') {
for (var i = 0, len = response.routes.length; i < len; i++) {
if (i === 0) {
directionsRenderer1.setDirections(response);
directionsRenderer1.setRouteIndex(i);
} else {
directionsRenderer2.setDirections(response);
directionsRenderer2.setRouteIndex(i);
}
}
console.log(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Here is my code. The first commented code does not draw and does not produce any errors. The second code throws an error:
InvalidValueError: at index 0: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value
I know that I am wrong and I am writing my code in the wrong place. I need help to show where the error is and how to fix it so that I understand.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
function showPosition(position) {
document.getElementById('mypos_lat').value=position.coords.latitude;
document.getElementById('mypos_lon').value=position.coords.longitude;
//alert("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude);
}
var darection = new google.maps.DirectionsRenderer;
function initialize() {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(38.583958, 68.780528),
mapTypeId: google.maps.MapTypeId.ROADMAP,
gestureHandling: "greedy",
fullscreenControl: false,
disableDefaultUI: true,
zoomControl: true,
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
darection.setMap(map);
google.maps.event.addListener(map, 'dragend', function() {
var centeral = map.getCenter();
//alert(centeral);
var names = centeral.toString();
var names =names.substr(1);
names = names.substring(0, names.length - 1);
console.log(names);
var re = /\s*,\s*/;
var nameList = names.split(re);
document.getElementById('bpos_lat').value=nameList[0];
document.getElementById('bpos_lon').value=nameList[1];
source_a = document.getElementById("mypos_lat").value;
source_b = document.getElementById("mypos_lon").value;
source_d = document.getElementById("bpos_lat").value;
source_e = document.getElementById("bpos_lon").value;
var darection = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//darection.setPanel(document.getElementById('panallocation'));
source = source_a + "," + source_b;
destination = source_d + "," + source_e;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
//Показ алтернативных дорог
provideRouteAlternatives: true
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
darection.setDirections(response);
}
});
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
distancefinel = distance.split(" ");
//start_addressfinel = start_address.split(" ");
// $('#distance').val(distancefinel[0]);
console.log(distancefinel[0]);
document.getElementById("distancesa").value = distancefinel[0];
////////// IN THIS STATE I WANT DRAW LINE ///////////////////
/*
function poliLines(map, source_a, source_b, source_d, source_e){
var routes = [
new google.maps.LatLng(source_a, source_b)
,new google.maps.LatLng(source_d, source_e)
];
var polyline = new google.maps.Polyline({
path: routes
, map: map
, strokeColor: '#ff0000'
, strokeWeight: 5
, strokeOpacity: 0.5
, clickable: false
});
*/
console.log(source);
console.log(destination);
var flightPlanCoordinates = [new google.maps.LatLng(source), new google.maps.LatLng(destination) ];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
} else {
alert("Unable to find the distance between selected locations");
}
});
}
);
$('<div/>').addClass('centerMarker').appendTo(map.getDiv())
//do something onclick
.click(function(){
var that=$(this);
if(!that.data('win')){
that.data('win',new google.maps.InfoWindow({content:'this is the center'}));
that.data('win').bindTo('position',map,'center');
}
that.data('win').open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Google maps v3 - Add markers at the center of tiles

function initialize() {
var myLatlng;
var mapOptions;
myLatlng = new google.maps.LatLng(29.98439980, -95.34140015);
mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
drawRectangle(map);
var result = {"regionList":[{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578}]};
alert(result);
addMarkersAtRegionCenter(map, result);
});
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for(var i=0; i<length; i++)
{
var image = result.regionList[i].imageIcon;
//alert("Latitude : " + result.regionList[i].centerLatitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude,result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() {
window.location.href = marker.url;
}
})(marker, i));
}
}
function drawRectangle(map) {
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var numberOfParts = 4;
var tileWidth = (northEast.lng() - southWest.lng()) / numberOfParts;
var tileHeight = (northEast.lat() - southWest.lat()) / numberOfParts;
for (var x = 0; x < numberOfParts; x++) {
for (var y = 0; y < numberOfParts; y++) {
var areaBounds = {
north: southWest.lat() + (tileHeight * (y+1)),
south: southWest.lat() + (tileHeight * y),
east: southWest.lng() + (tileWidth * (x+1)),
west: southWest.lng() + (tileWidth * x)
};
var area = new google.maps.Rectangle({
strokeColor: '#FF0000',
//strokeOpacity: 0.8,
strokeWeight: 2,
//fillColor: '#FF0000',
//fillOpacity: 0.35,
map: map,
bounds: areaBounds
});
}
}
}
}
google.maps.event.addDomListener(window, "load", initialize);
In the above code, I am trying to add markers at the center of each rectangle. But I am not able to add markers. I have hard coded image icon value since I don't have image mentioned in the array.
Thanks in advance for your help.
Related question: Google maps api v3 - divide region into equal parts using tiles
Simpler to add the markers to the centers of the rectangles when you create them:
var centerMark = new google.maps.Marker({
position: area.getBounds().getCenter(),
map: map
});
proof of concept fiddle
To add the markers from the response to the map (the positions in the posted response are not at the center of the squares), this is the same function you posted in your question, it works for me (the blue markers), I modified your click listener to open an infowindow (rather than do a redirect of the page):
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for (var i = 0; i < length; i++) {
var image = result.regionList[i].imageIcon;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude, result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// window.location.href = marker.url;
infowindow.setContent("regionList:" + i + "<br>centLat=" + result.regionList[i].centerLatitude + "<br>centLng=" + result.regionList[i].centerLongitude + "<br>imageIcon=" + result.regionList[i].imageIcon + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
}
})(marker, i));
}
}

Google Maps 2 InfoWindows Auto-Opening infoWindow, 1 infoWindow after click

I have an auto-opening infoWindow.
I wish only two were opened automatically, while one did not. The effect Just like in the pictures.
My Code:
<script>
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3],
['Oddział', 52.812224, 17.201023, 2],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function () {
if(openedInfoWindow[i] != null){
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
}else{
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
google.maps.event.trigger(marker, 'click');
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyADTnbl7e9y2o13cXkUFO8RZpXFJI-yzp4&' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>`
Picture 1 = so now
Picture 2 = so it has to be
I would suggest you generalize it, add a member to your array to determine whether to open the marker or not.
var locations = [
// IW content, lat, lng, nowrap, open IW
['Oddział', 52.846190, 17.723237, 3, true],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, false]
];
Then do this to open the infowindow:
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
proof of concept fiddle
code snippet:
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3, false],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, true]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function() {
if (openedInfoWindow[i] != null) {
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
} else {
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Polylines is not coming perfectly on google map in ios [duplicate]

I am trying to get a polyline on a Google map after getting directions. I want to use the v3_epoly to place markers along a polyline.
I found this post, which worked, but I found it wasn't completely accurate. In the image, the Google directions is the light blue and the polyline is the darker blue:
You can see it's quite inaccurate.
This is the code:
directions_service.route(req, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
path = response.routes[0].overview_path;
$(path).each(function(index, item) {
route.getPath().push(item);
bounds.extend(item);
});
route.setMap(map);
map.fitBounds(bounds);
directions_display.setDirections(response);
}
});
Anyone know either how to improve this accuracy or to get the polyline another way?
EDIT:
I wanted to add the code that got it working:
legs = response.routes[0].legs;
$(legs).each(function(index, item) {
steps = item.steps;
$(steps).each(function(index, item) {
path = item.path;
$(path).each(function(index, item) {
route.getPath().push(item);
counter++;
bounds.extend(item);
});
});
});
Don't use overview_path for the polyline, it doesn't include all the points, grab the points out of all the legs and use them to create the polyline.
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
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);
example
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(51.276092, 1.028938),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true
});
directionsService.route({
origin: new google.maps.LatLng(51.269776, 1.061326),
destination: new google.maps.LatLng(51.30118, 0.926486),
waypoints: [{
stopover: false,
location: new google.maps.LatLng(51.263439, 1.03489)
}],
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
// directionsDisplay.setDirections(response);
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#0000FF',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
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);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

Finding the great circle distance between three points using the Google Maps API v3

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>");
}