Google maps displaying other side of the planet - google-maps

I have literally been trying anything and everything, but the map displays somewhere in Antarctica, when the coordinates that I am receiving, are for cities in the US.
The following is the code that inits the map:
$(window).on('load', function() {
// eslint-disable-next-line
function initTest() {
var fastestCitiesApi = JSON.parse(document.getElementById('fastestCitiesApi').value);
console.log(fastestCitiesApi);
var tempLatLng = fastestCitiesApi[0]['latLng'];
console.log(tempLatLng);
var latLng = tempLatLng.split(',');
console.log('latLng[0]: ' + latLng[0]);
console.log('latLng[1]: ' + latLng[1]);
const myLatLng = new google.maps.LatLng({ lat: parseFloat(latLng[0]), lng: parseFloat(latLng[1]) });
const mapOptions = {
zoom: 4,
center: myLatLng
};
const map = new google.maps.Map(document.getElementById('fastest_cities_map'), mapOptions);
new google.maps.Marker({
position: myLatLng,
map,
title: 'somewhere',
});
}
initTest();
});
As you can see by the following screen shot of the console is showing, that the coordinates are 36, 78 - which when I do a look up on google for Boydton, VA - those are the coordinates that is returned - link to google search for Boydton, VA lat long
As you can see by the screen shot, I have zero errors. What am I doing wrong?
Thanks in advance

Thanks to #Gray pointing out that the long should be negative, the rest of the array loaded up the markers as expected.
Here's the final code:
$(window).on('load', function() {
// eslint-disable-next-line
function initTest() {
/* init vars */
const map = new google.maps.Map(document.getElementById('fastest_cities_map'));
var fastestCitiesApi = JSON.parse(document.getElementById('fastestCitiesApi').value);
// console.log(fastestCitiesApi);
var tempLatLng = '';
var latLng = [];
var markerOptionsArray = new Array();
var latlngArray = new Array();
var myLat = new Array();
var myLng = new Array();
var markers = [];
var nameArray = [];
var infowindow = new google.maps.InfoWindow({maxWidth: 350});
/* create arrays for markers */
for(var item in fastestCitiesApi) {
tempLatLng = fastestCitiesApi[item]['latLng'];
nameArray.push(fastestCitiesApi[item]['city']);
// console.log(tempLatLng);
latLng = tempLatLng.split(',');
myLat.push(latLng[0]);
myLng.push(latLng[1]);
// console.log('latLng[0]: ' + latLng[0]);
// console.log('latLng[1]: ' + latLng[1]);
markers.push({
lat: myLat[item],
lng: myLng[item],
name: nameArray[item],
});
}
// console.log('markers: ' + JSON.stringify(markers));
var bounds = new google.maps.LatLngBounds();
for (var v=0; v<markers.length; v++)
{
var secheltLoc = new google.maps.LatLng(markers[v].lat, markers[v].lng);
var myOptions = {
content: markers[v].name
,boxStyle: {
border: "none"
,textAlign: "center"
,fontSize: "12pt"
,width: "120px"
}
,disableAutoPan: true
,pixelOffset: new google.maps.Size(-50, 0)
,position: secheltLoc
,closeBoxURL: ""
,isHidden: false
,pane: "mapPane"
,enableEventPropagation: true
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[v].lat, markers[v].lng),
map: map,
center: new google.maps.LatLng(markers[v].lat, markers[v].lng)
});
google.maps.event.addListener(marker, 'click', (function (marker, v) {
return function () {
infowindow.setContent(markers[v].name);
infowindow.open(map, marker);
}
})(marker, v));
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
marker.open = false;
});
bounds.extend(new google.maps.LatLng(markers[v].lat, markers[v].lng));
myLatLng = markers[v].lat+','+markers[v].lng;
}
map.fitBounds(bounds);
}
// alert(google.maps.Map);
initTest();
});
The following is a screen shot of the result of the eight city array:

Related

Can I use the google maps javascript api to display both points and polylines?

I am in the middle of a coding an asset map for one of my customers assets.
The database contain information as below in two tables
tblAssets
AssetID
AssetName
AssetLocation
AssetLat
AssetLng
AssetType
tblAssetLinks
LinkID
LinkType
LinkLat1
LinkLng1
LinkLat2
LinkLng2
tblAssets is used to plot the individual assets, these contain other information (irrelevant to this issue) and tblAssetLinks in their current application draws a line between LinkLat1, LinkLng1 and LinkLat2, LinkLng2
I have managed to get tblAssets to plot loading the db as an xml array as below
<markers>
<marker PrimaryKey="175223" NodeName="TQ88768407" distance="0.0123043158297526" lat="51.455662" lng="0.716716" Type="NODE"/>
<marker PrimaryKey="175221" NodeName="TQ88768405" distance="0.0175958000932205" lat="51.455498" lng="0.716893" Type="NODE"/>
<marker PrimaryKey="175226" NodeName="TQ88768411" distance="0.023174171700034" lat="51.455791" lng="0.716119" Type="NODE"/>
</markers>
This is the javascript i am using to load my points onto my map
<script type="text/javascript">
//<![CDATA[
var customIcons = {
OTHER: {
icon: 'images/other.png'
}
};
function load() {
//map.addMapType(G_SATELLITE_3D_MAP);
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(51.4555503, 0.7164931),
zoom: 18,
mapTypeId: 'hybrid'
});
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("xmlgen_asset.php?lat=51.4555503&lng=0.7164931", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var primarykey = markers[i].getAttribute("PrimaryKey");
var nodename = markers[i].getAttribute("NodeName");
var ownedby = markers[i].getAttribute("OwnedBy");
var nodeid = markers[i].getAttribute("NodeID");
var type = markers[i].getAttribute("Type");
var lat = markers[i].getAttribute("lat");
var lng = markers[i].getAttribute("lng");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = nodename + "<br/>" + type;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
I was wondering if there was a way for me to load another xml with tblAssetLinks to draw polylines as well as the points above onto the map?
To parse that XML, get each link element, retrieve their lat1/lng1 and lat2/lng2 attributes and make polylines from them (per the example in the documentation.
var polydata = xml.getElementsByTagName('link');
for (var i = 0; i < polydata.length; i++) {
var pt1 = {
lat: parseFloat(polydata[i].getAttribute("lat1")),
lng: parseFloat(polydata[i].getAttribute("lng1"))
}
var pt2 = {
lat: parseFloat(polydata[i].getAttribute("lat2")),
lng: parseFloat(polydata[i].getAttribute("lng2"))
}
var polyline = new google.maps.Polyline({
path: [pt1, pt2],
map: map
});
}
proof of concept fiddle
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(51, 0),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var xml = xmlParse(xmlData);
var polydata = xml.getElementsByTagName('link');
for (var i = 0; i < polydata.length; i++) {
var pt1 = {
lat: parseFloat(polydata[i].getAttribute("lat1")),
lng: parseFloat(polydata[i].getAttribute("lng1"))
}
var pt2 = {
lat: parseFloat(polydata[i].getAttribute("lat2")),
lng: parseFloat(polydata[i].getAttribute("lng2"))
}
var polyline = new google.maps.Polyline({
path: [pt1, pt2],
map: map
});
bounds.extend(polyline.getPath().getAt(0));
bounds.extend(polyline.getPath().getAt(1));
}
map.fitBounds(bounds);
}
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
google.maps.event.addDomListener(window, "load", initialize);
var xmlData = '<links><link PrimaryKey="56669" OwnedBy="SWS" AssetID="30757610" distance="0.0161501151649766" lat1="51.455479" lng1="0.716877" lat2="51.455498" lng2="0.716893" Type="COMBINED"/><link PrimaryKey="45827" OwnedBy="SWS" AssetID="1386010" distance="0.024165762230059" lat1="51.455791" lng1="0.716119" lat2="51.455769" lng2="0.716060" Type="COMBINED"/><link PrimaryKey="92131" OwnedBy="SWS" AssetID="30757581" distance="0.0258313521247188" lat1="51.455750" lng1="0.716015" lat2="51.455734" lng2="0.716000" Type="COMBINED"/><link PrimaryKey="55871" OwnedBy="SWS" AssetID="30757590" distance="0.033043902136047" lat1="51.455833" lng1="0.715905" lat2="51.455853" lng2="0.715906" Type="SURFACE_WATER"/><link PrimaryKey="79135" OwnedBy="SWS" AssetID="1386511" distance="0.0387150798069927" lat1="51.455372" lng1="0.715662" lat2="51.455509" lng2="0.715598" Type="COMBINED"/><link PrimaryKey="55870" OwnedBy="SWS" AssetID="30757560" distance="0.039789930528151" lat1="51.455353" lng1="0.715646" lat2="51.455372" lng2="0.715662" Type="COMBINED"/><link PrimaryKey="79136" OwnedBy="SWS" AssetID="1386531" distance="0.0415342089389798" lat1="51.455051" lng1="0.717068" lat2="51.454903" lng2="0.716886" Type="COMBINED"/><link PrimaryKey="79062" OwnedBy="SWS" AssetID="1386001" distance="0.0424351462005461" lat1="51.455944" lng1="0.715768" lat2="51.455917" lng2="0.715723" Type="SURFACE_WATER"/><link PrimaryKey="2812" OwnedBy="SWS" AssetID="1385989" distance="0.042520172377456" lat1="51.455795" lng1="0.715615" lat2="51.455692" lng2="0.715767" Type="COMBINED"/><link PrimaryKey="4041" OwnedBy="SWS" AssetID="1386420" distance="0.043199028781749" lat1="51.456078" lng1="0.717043" lat2="51.455662" lng2="0.716716" Type="COMBINED"/></links>';
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Refresh DownloadUrl on google map v3 and remove old markers

Hi I had a script and a xml file with 10.000 markers in it. I use markercluster to display the markers, but in order to fill the mobile browsers requierement I must begin the map at a certain zoom level (not to display to many markers). So I want to dynamically load the markers when the user change the zoom or viewport.
Here is my script. I thing I can't get the lat and lng of the LatLngBounds of the current viewport :
var customIcons = {
chambrehote: {
icon: '/wp-content/themes/codium-extend/images/chambre.png',
shadow: '/wp-content/themes/codium-extend/images/icon-shadow.png'
}
};
function initialize() {
var cluster = [];
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng('45.7676067','4.8351733'),
scrollwheel: false,
zoom: 12,
mapTypeId: 'roadmap'
});
var mcOptions = {gridSize: 100, styles: [
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m1.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m2.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m3.png",
width: 90
}
]};
var infoWindow = new google.maps.InfoWindow;
var bounds = new google.maps.LatLngBounds();
var swPoint = bounds.getSouthWest();
var nePoint = bounds.getNorthEast();
var swLat = swPoint.lat();
var swLng = swPoint.lng();
var neLat = nePoint.lat();
var neLng = nePoint.lng();
downloadUrl("/wp-content/themes/codium-extend/search/search_chambres.php?&type=chambrehote&codgeo=<?php echo $CODGEO ; ?>&radius=200&lat1="+swLat+"&lng1="+swLng+"&lat2="+neLat+"&lng2="+neLng+"", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("ville");
var slug = markers[i].getAttribute("slug");
var stars = markers[i].getAttribute("stars");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> " + "<br/>" + "" + "><a href=" + "/chambre-d-hote/" + slug + "/>lien vers la fiche</a>";
var icon = customIcons[type] || {};
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
//bounds.extend(point);
//map.fitBounds(bounds);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() { infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster,mcOptions);
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
function changePosition() {
var position = document.getElementById('position').value;
adUnit.setPosition(google.maps.ControlPosition[position]);
}
First point :
I think I couldn't get the value of swLat, swLng... for passing them to downloadUrl
And second point I certainly miss a listener somewhere but don't know where !
Thanks for your inputs
---- EDIT ----
Right now I can load dynamically the data when the idle is changed, but (there is a but) now each change a new marker is add even if it's already on the map. Is there a way to clean all the markers when the idle change before loading the new ones?
var cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: new google.maps.LatLng('45.7676067','4.8351733'),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var mcOptions = {gridSize: 100, styles: [
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m1.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m2.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m3.png",
width: 90
}
]};
var infoWindow = new google.maps.InfoWindow;
google.maps.event.addListener(map, 'idle', function() {
var bounds = map.getBounds();
var swPoint = bounds.getSouthWest();
var nePoint = bounds.getNorthEast();
var swLat = swPoint.lat();
var swLng = swPoint.lng();
var neLat = nePoint.lat();
var neLng = nePoint.lng();
// alert(swLng);
downloadUrl("/wp-content/themes/codium-extend/search/search_chambres.php?lat=45.7676067&lng=4.8351733&type=chambrehote&codgeo=<?php echo $CODGEO ; ?>&radius=2000&lat1="+swLat+"&lng1="+swLng+"&lat2="+neLat+"&lng2="+neLng+"", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("ville");
var slug = markers[i].getAttribute("slug");
var stars = markers[i].getAttribute("stars");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> " + "<br/>" + "" + "><a href=" + "/chambre-d-hote/" + slug + "/>lien vers la fiche</a>";
var icon = customIcons[type] || {};
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
//bounds.extend(point);
//map.fitBounds(bounds);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster,mcOptions);
});
});
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
function changeFormat() {
var format = document.getElementById('format').value;
adUnit.setFormat(google.maps.adsense.AdFormat[format]);
}
function changePosition() {
var position = document.getElementById('position').value;
adUnit.setPosition(google.maps.ControlPosition[position]);
}

Display multiple routes on google map

I am trying to show multiple routes on google map but It is showing only one. Can you please what I am doing wrong?
<div class="searchmap" style="float:left;margin-left:1%" id="map"></div>
var map = null;
var markerPoints = [];
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById("map"), {scrollwheel:false, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, center:new google.maps.LatLng(19.0759837, 72.87765590000004), zoom:13});
directionsDisplay.setMap(map);
}
function calcRoute(flat, flng, tlat, tlng)
{
var start = new google.maps.LatLng(flat, flng);
var end = new google.maps.LatLng(tlat, tlng);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false,
suppressInfoWindows: true
});
directionsDisplay.setMap(map);
directionsService.route(request, function(result, status) {
console.log(result);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
calcRoute("19.210430", "72.843422", "19.109858", "72.878433");
calcRoute("19.228977", "72.856812", "19.117302", "72.884041");
Can you please let me know what I am doing wrong?
Display multiple routes on google map with waypoints and direction arrow
==============
Click here!
![In image u can see 2 routes with direction arrow][1]
<style>
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var directionsService;
var stepDisplay;
var position;
var marker = [];
var polyline = [];
var poly2 = [];
var poly = null;
var startLocation = [];
var endLocation = [];
var timerHandle = [];
var stops_data = [[ {"Geometry":{"Latitude":23.05242,"Longitude":72.53375}},
{"Geometry":{"Latitude":23.03007,"Longitude":72.59664}}
] ,[ {"Geometry":{"Latitude":23.00959,"Longitude":72.56189}},
{"Geometry":{"Latitude":23.05754,"Longitude":72.55302}}
]];
var a,z,b;
var add;
var speed = 0.000005, wait = 1;
var infowindow = null;
infowindow = new google.maps.InfoWindow();
var myPano;
var panoClient;
var nextPanoId;
var directionsDisplay = [];
directionsDisplay[0] = new window.google.maps.DirectionsRenderer({
suppressMarkers: true
});
directionsDisplay[1] = new window.google.maps.DirectionsRenderer({
suppressMarkers: true
});
var map;
var mapOptions = { center: new google.maps.LatLng(42.5584308, -70.8597732), zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initialize()
{
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsService = new google.maps.DirectionsService();
// Setroute(locations[0],locations[1],directionsDisplay[0]);
// Setroute(locations2[0],locations2[1],directionsDisplay[1]);
Tour_startUp(stops_data[0]);
window.tour.loadMap(map, directionsDisplay[0]);
window.tour.fitBounds(stops_data[0],map);
if (stops_data[0].length > 1)
window.tour.calcRoute(stops_data[0],directionsService, directionsDisplay[0]);
Tour_startUp(stops_data[1]);
window.tour.loadMap(map, directionsDisplay[1]);
window.tour.calcRoute(stops_data[1],directionsService, directionsDisplay[1]);
window.tour.fitBounds(stops_data[1],map);
}
function fx(o)
{
if(o && o.legs)
{
for(l=0;l<o.legs.length;l++)
{
var leg=o.legs[l];
for(var s=0;s<leg.steps.length;++s)
{
var step=leg.steps[s],
a=(step.lat_lngs.length)?step.lat_lngs[0]:step.start_point,
z=(step.lat_lngs.length)?step.lat_lngs[1]:step.end_point,
dir=((Math.atan2(z.lng()-a.lng(),z.lat()-a.lat())*180)/Math.PI)+360,
ico=((dir-(dir%3))%120);
new google.maps.Marker({
position: a,
icon: new google.maps.MarkerImage('http://maps.google.com/mapfiles/dir_'+ico+'.png',
new google.maps.Size(24,24),
new google.maps.Point(0,0),
new google.maps.Point(12,12)
),
map: map,
title: Math.round((dir>360)?dir-360:dir)+'°'
});
}
}
}
}
function Tour_startUp(stops) {
// alert('first'+stops.length);
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, dirdis) {
var myOptions = {
zoom: 15,
center: new window.google.maps.LatLng(51.507937, -0.076188), // default to London
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
dirdis.setMap(map);
},
fitBounds: function (stops_data,map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
for( var x in stops_data) {
var myLatlng = new window.google.maps.LatLng(stops_data[x].Geometry.Latitude, stops_data[x].Geometry.Longitude);
bounds.extend(myLatlng);
}
map.fitBounds(bounds);
},
calcRoute: function (stops_new,directionsService, dirdis) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops_new.length > 0;
var time= [];
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
// alert('second'+stops_new.length);
//alert(stops_new[0].Geometry.Latitude +' ===== ' +stops_new[0].Geometry.Longitude);
for (var j = itemsCounter; j < stops_new.length; j++) {
subitemsCounter++;
//alert(stops[j].Geometry.Time);
subBatch.push({
location: new window.google.maps.LatLng(stops_new[j].Geometry.Latitude, stops_new[j].Geometry.Longitude),
stopover: true
});
//time.push(stops[j].Geometry.Time);
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops_new.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
};
// alert('start'+start);
// alert('end'+end);
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
fx(result.routes[0]);
polyline[0] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
poly2[0] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
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++;
}
}
}
dirdis.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
var path = combinedResults.routes[0].overview_path;
//alert(path.length);
// alert(legs.length);
//setRoutes(legs[0].start_location,legs[legs.length-1].end_location);
for (var i=0; i < legs.length;i++)
{
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
if (i == 0) {
//marker[0] = createMarker2(legs[i].start_location,"start",legs[i].start_address,"green");
}
var steps = legs[i].steps;
// alert('arrival time : '+legs[i].arrival_time.text);
// var duration = steps.duration_in_traffic;
// alert(duration.text);
for (j=0;j<steps.length;j++)
{
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++)
{
polyline[0].getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
}
}
// createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);
}
// Marker for start point
createMarker(dirdis.getMap(),legs[0].start_location,"marker"+0,"Start Point<br>"+legs[0].start_address,'A');
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
// marker for End Point
createMarker(dirdis.getMap(),legs[legs.length-1].end_location,"marker"+i,"End Point <br>"+legs[legs.length-1].end_address,'B');
polyline[0].setMap(map);
//startAnimation(0);
}
}
});
})(k);
}
}
};
}
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) {
//alert(iconStr);
if ((typeof(iconStr)=="undefined") || (iconStr==null)) {
iconStr = "red";
}
if(iconStr == 'A')
{
// for start point
if (!icons[iconStr]) {
icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/dd-start.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));
}
}
if (iconStr == 'B')
{
// for end point
if (!icons[iconStr]) {
icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/dd-end.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(color);
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
// alert('creatMarker'+contentString);
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;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map_canvas"></div>
[1]: http://i.stack.imgur.com/yB4Tw.png
Here you go.. the full explaination , credit goes to the author
function drawMap() {
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = new google.maps.LatLng(51.47482547819850,-0.37739553384529);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: start
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
}
function requestDirections(start, end) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
});
}
requestDirections('(51.47482547819850,-0.37739553384529)', '(51.59512428598160,-0.17190814889409)');
requestDirections('EC1V 0AH', '(51.47615506206120, -0.37795315370703)');
}
you need to create an instance of google.maps.DirectionsRenderer(); EVERYTIME you draw the route to make it visible ;)
Your directionsDisplay variable is an instance of google.maps.DirectionsRenderer() and that can only hold one set of directions at a time. If you want to display more than one route, you need multiple google.maps.DirectionsRenderer().
To get multiple routes we can add provideRouteAlternatives = true inside request object while calling route() of DirectionsService object. See Directions Requests.
This method will return array of routes if available with their name in summary key.
Now we can display these routes on view and on click of each route we can pass route object and can render the direction by setDirections() of DirectionsRenderer object. See Displaying the DirectionsResult
try this code
<!DOCTYPE html>
<html>
<head>
<title>Waypoints in Directions</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=your-key&callback=initMap&libraries=&v=weekly"
defer
></script>
<style type="text/css">
html,
body {
height: 99%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
float: left;
width: 99%;
height: 100%;
}
</style>
<script>
"use strict";
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
center: {
lat: 19.8762,
lng: 75.3433
}
});
const directionsService = new google.maps.DirectionsService();
let points = [
{
origin: {
lat: 19.9974533,
lng: 73.78980229999999
},
destination: {
lat: 19.0759837,
lng: 72.8776559
},
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
},
{
origin: {
lat: 21.1458,
lng: 79.0882
},
destination: {
lat: 18.5204,
lng: 73.8567
},
// waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}
]
for (var i = 0; i < points.length; i++) {
calculateAndDisplayRoute(directionsService,points[i])
}
function calculateAndDisplayRoute(directionsService,points) {
let directionsRenderer = new google.maps.DirectionsRenderer();
// const waypts = [{
// location: {
// lat: 19.8762,
// lng: 75.3433
// },
// },
// ];
directionsService.route(
points,
(response, status) => {
console.log(response);
if (status === "OK") {
directionsRenderer.setDirections(response);
directionsRenderer.setMap(map);
} else {
window.alert("Directions request failed due to " + status);
}
}
);
}
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Google Maps API v3 - Arrays and InfoWindows

I'm been trying to make an infowindow for each of my markers for a while now but cant get it to work.
This is what I came up with:
for(var i=0; i<markery.length; i++)
{
var latt = parseFloat(markery[i].attributes.getNamedItem("lat").nodeValue);
var lon = parseFloat(markery[i].attributes.getNamedItem("lon").nodeValue);
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
var nazwa = markery[i].attributes.getNamedItem("nazwa").nodeValue;
var rozmiar = new google.maps.Size(30,23);
var punkt_startowy = new google.maps.Point(0,0);
var punkt_zaczepienia = new google.maps.Point(15,12);
var ikona = new google.maps.MarkerImage(ikona_url, rozmiar, punkt_startowy, punkt_zaczepienia);
markert.push(new google.maps.Marker({
position: new google.maps.LatLng(latt,lon),
title: nazwa,
icon: ikona,
map: map,
content: nazwa
}));
google.maps.event.addListener(marker, 'click', function() {
var info = new google.maps.InfoWindow({content: this.content});
});
}
And the full code is:
<script type="text/javascript">
var map;
var marker1;
var markert = [];
var lati;
var loni;
var infowindow;
I start the map:
function initialize() {
lat = 50.42952;
long = 15.60059;
var latlng = new google.maps.LatLng(lat, long);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor:'crosshair',
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
dymek = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function(event) {
add_marker(event.latLng, 'Your new marker', 'Your new marker' );
});
}
This function gets the address of the clicked point:
function findAddress(event) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: event.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infoWindow.setContent(results[0].formatted_address);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
}
});
}
This function adds a new marker on the map where I clicked:
function add_marker( pos, pos_title, pos_str ) {
marker1 = new google.maps.Marker( {
position: pos,
map: map,
draggable: true,
title: pos_title
});
map.setZoom(15);
map.setCenter(marker1.getPosition());
LoadMarkers();
}
This function loads the nearby points that are near the marker I created in the function above:
function LoadMarkers()
{
var adres='add.xml?lat='+lati+'&long='+loni;
jx.load(adres, function(xml)
{
var markery = xml.getElementsByTagName("marker");
for(var i=0; i<markery.length; i++)
{
var latt = parseFloat(markery[i].attributes.getNamedItem("lat").nodeValue);
var lon = parseFloat(markery[i].attributes.getNamedItem("lon").nodeValue);
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
var nazwa = markery[i].attributes.getNamedItem("nazwa").nodeValue;
var markert = addMarkers(latt,lon,ikona_url,nazwa);
}
},'xml','get');
}
This function actually ads the nearby markers on the map. These markers are the ones that I want the infowindow to show:
function addMarkers(latt,lon,ikona_url,nazwa)
{
var rozmiar = new google.maps.Size(30,23);
var punkt_startowy = new google.maps.Point(0,0);
var punkt_zaczepienia = new google.maps.Point(15,12);
var ikona = new google.maps.MarkerImage(ikona_url, rozmiar, punkt_startowy, punkt_zaczepienia);
markert.push(new google.maps.Marker({
position: new google.maps.LatLng(latt,lon),
title: nazwa,
icon: ikona,
map: map,
animation: google.maps.Animation.DROP }));
google.maps.event.addListener(markert, 'tilesloaded', function() {
var info = new google.maps.InfoWindow({content: nazwa});
});
}
You're not actually opening the infowindow at any point. Please review this documentation and example, and adapt your code accordingly. You actually need to use the open method for infowindow.

Markers render more than once

i've implemented google maps v3, it updates while bounds_changed event but the problem is when the event triggers it renders the markers more than once, any suggestions.
i've added the makers to marker manager.
var map = null;
var myLatLng = null;
var sidebarHtml = "";
var infowindow = infowindow = new google.maps.InfoWindow({});;
var mgr = null;
var currentBounds = null;
var xml = null;
var markers = null;
var markersArray = [];
var customIcons = {
restaurant: {
icon: 'images/icon_01.png'
},
bar: {
icon: 'images/icon_02.png'
}
}
function load() {
var myOptions = ({
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
mgr = new MarkerManager(map, {fitBounds: true});
google.maps.event.addListener(map, 'bounds_changed', downloadUrl);
}
function downloadUrl() {
var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest;
var params = "";
var url = "phpmysqlajax_genxml.php";
request.onreadystatechange = function() {
if(request.readyState == 4) {
//alert(request.responseXML);
useTheData(request);
}
};
request.open("GET", url + params, true);
request.send(null);
}
function useTheData(data) {
currentBounds = map.getBounds();
xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
mgr.clearMarkers();
if (!currentBounds) currentBounds = new google.maps.LatLngBounds();
sidebarHtml = '<ul class="sidebar">';
for(var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var type = markers[i].getAttribute("type");
var latlng = new google.maps.LatLng(lat, lng);
if (currentBounds.contains(latlng)) {
attachMarker( name, address, latlng, type );
markerSidebarEntry(i);
}
}
sidebarHtml += "</ul>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
};
function attachMarker( name, address, latlng, type ) {
var marker = new google.maps.Marker({
position : latlng,
map: map,
icon : customIcons[type].icon
});
mgr.addMarker(marker, 5);
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent( address );
infowindow.open(map, this);
});
// add marker here.
}
function markerSidebarEntry(i) {
var name = markers[i].getAttribute("name");
sidebarHtml += '<li class="' + markers[i].getAttribute("type") + '">' + name + '</li>';
}
function markerClick(i) {
google.maps.event.trigger(markersArray[i], "click");
}
It may just be a copy-paste error, but this code doesn't seem correct (double-declaration of 'infowindow' and duplicated ; at the end):
var infowindow = infowindow = new google.maps.InfoWindow({});;
Also here you don't need the () surrounding the {}
var myOptions = ({
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
Suggest you run your JS code through something like JSLint.