Create a google maps link from API Map with multiple waypoint - javascript

I have built a web app that uses the google maps v3 API to build a map with directions multiple waypoints.
jQuery.getJSON(driverURL, function(dData){
var routeObject = {};
var lat = dData.Location.lat;
var lng = dData.Location.lng;
routeObject.origin = new google.maps.LatLng(lat, lng);
routeObject.destination = new google.maps.LatLng(endRoute.lat, endRoute.lng);
routeObject.waypoints = waypoints;
routeObject.travelMode = google.maps.TravelMode.DRIVING;
routeObject.optimizeWaypoints = true;
directionsService.route(routeObject, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: colors[driverLines.length]
}
});
directionsDisplay.setMap(dMap);
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
I have the Map, the waypoints, the start and the end all stored, but I'd like to be able to generate a google maps clickable link to the directions for this route that I can send to users. I can find how to send a link with a single marker, but not how to generate a map link with the full route direction.
Any help appreciated.

I figured this out, and it's actually easier than I thought, but took some doing.
First I took some of the waypoints I had, as addresses, not lat/lng points, and built a route map on maps.google.com. Then I looked at how the URL for that map was constructed. Very simple to re-create.
The URL is just http://maps.google.com/dir/starting address as address,city,state,zip/waypoint as address,city,state,zip/waypoint/ending address as address,city,state,zip And you're done. If you're using lat/lng coordinates for your start,waypoint,end locations you'll have to first geo-code them using the V3 api then extract the address information from the returned result and insert those in your URL, but it works.
Here's how I made the final link that has a start, a bunch of waypoints, and an ending location. I start with a JSON object, called Data, that has all the address info in it and build a long string from it, in the format Google Maps expects:
var dirs = ''
for(var x = 0; x<Data.length;x++){
dirs += Data[x].Address + "," + Data[x].City + "," + Data[x].State + "," + Data[x].Zip + "/";
}
Then, I add the start and end locations to it:
var dirLink = 'http://maps.google.com/maps/dir/';
dirLink += start.Address + "," + start.City + "," + start.State + "," + start.Zip + "/" + dirs + end.Address + "," + end.City + "," + end.State + "," + end.Zip;
And dirLink will be a complete link that will give directions from start.Address through all the waypoints to end.Address.

Don`t forget for
In script :
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(51.509865, -0.118092),
pointC = new google.maps.LatLng(50.8429, -0.1313),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
}),
markerC = new google.maps.Marker({
position: pointC,
title: "point C",
label: "C",
map: map
});
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, pointC);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, pointC) {
var first = new google.maps.LatLng(51.509865, -0.118092); //we can get them from params.
var request = {
origin: pointA,
destination: pointC,
waypoints: [{location: first, stopover: false}
], //here array of waypoints
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
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 />";
}
} else {
alert("directions response " + status);
}
});
}
initMap();

Related

Access javascript variable

I'am trying to create a web app with google map direction API,In a variablesummaryPanel.innerHTMLContains the details regarding the address and distance.I required to use distance for other calculations ,so how can i access the variable,can we access the variable from the angular controller?
script.js
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === '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>';
console.log(summaryPanel.innerHTML);//Variable required to access
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
Using jQuery:
var htmlString = $(summaryPanel).html();
Then you'll have to parse whatever htmlString comes out to, but it will have what you're looking for.
Source: http://api.jquery.com/html/

google maps javascript api does not get me any adress

I am using this code ,
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, 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>';
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
above code works fine.But when I changed the part below,it gives me error code "Directions request failed due to zero_results".because of it can not find this coordinat (36.9165612, 34.895210200000065) in map.But actually I am getting this coordinats another google api.so this coordinat exists.Even it finds the address in google map https://www.google.com.tr/maps/place/36.9165612,+34.895210200000065/data=!4m2!3m1!1s0x0:0x0?sa=X&ved=0ahUKEwiB6OT03JjNAhWLLMAKHZrIApgQ8gEIGjAA
lastly when I change to coordinat to (41.85, -87.65), it works fine coz it finds the address.Many less coordinats works like this.
I want to find all coordinats in google maps.
How can I solve this problem?
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: new google.maps.LatLng(36.9165612, 34.895210200000065),
stopover: true
});
}
}
It may not find an address from a lat and lng. You have to consider it.
More info here and here

Google geocoder service is not returning appropriate lat and long values with javascript

Google map is not showing the exact location. I'm taking the address from our clients and will display them the map. I cross checked the google lat and long with mine, it is not returning the exact values. Here is my code, if I am wrong, please guide me.
function callMap() {
var fullAddress = address + "," + city + "," + state + "," + zip;
var lat_Company = "";
var lng_Company = "";
geocoder.geocode({
'address': fullAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat_Company = parseFloat(results[0].geometry.location.lat());
lng_Company = parseFloat(results[0].geometry.location.lng());
var lCompanyObject = new Object();
lCompanyObject.Name = companyDetails.CompanyName;
lCompanyObject.Description = address + "<br/>" + city + ", " + state + "," + zip;
lCompanyObject.FullAddress = address + ", " + city + ", " + state + "," + zip;
lCompanyObject.Lat = lat_Company;
lCompanyObject.Lng = lng_Company;
displayCompany(city, state, "comp_map", "mapinfowindow", lCompanyObject, "fromSideBar");
}
});
var abpoutsideBarBuilder = '<ul>' +
'<li><div id="map_wrapper1">' +
'<div id="comp_map1"></div>' +
'<div id="mapinfowindow"style="display:none" ><b>#name</b><br>#description</div></div></li></ul>';
$('.about_map_addr_businesshours').html(abpoutsideBarBuilder);
}
function displayCompany(pCity, pState, pMapDiv, mapinfowindow, lCompany, from) {
var requestLocation = lCompany.FullAddress;
geocoder.geocode({
'address': requestLocation
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = parseFloat(results[0].geometry.location.lat());
var lng = parseFloat(results[0].geometry.location.lng());
if (lat != null && lng != null) {
centerLat = lat;
centerLng = lng;
initDisplayMap(centerLat, centerLng, pMapDiv, mapinfowindow, lCompany, from);
}
} else {
console.error("Geocode was not successful for the following reason ::" + status);
}
});
}
function initDisplayMap(pCenterLat, pCenterLng, pMapDiv, mapinfowindow, pCompany, from) {
if ($("#" + mapinfowindow).length > 0) {
var latlng = new google.maps.LatLng(pCenterLat, pCenterLng);
var myOptions = {
zoom: 14,
center: latlng,
disableDefaultUI: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(pMapDiv), myOptions);
var infowindow = null;
infowindow = new google.maps.InfoWindow({});
var LatLngList = new Array();
var marker = pCompany;
var markerHTML = $('#mapinfowindow').clone().html();
if (from.indexOf("fromSideBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
} else if (from.indexOf("fromAboutBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
}
if (marker.Lat != null && marker.Lng != null) {
var myLatLng = new google.maps.LatLng(marker.Lat, marker.Lng);
LatLngList[LatLngList.length] = myLatLng;
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
clickable: true,
html: markerHTML
});
google.maps.event.addListener(beachMarker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
var bounds = new google.maps.LatLngBounds();
if (LatLngList.length > 1) {
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend(LatLngList[i]);
}
//Fit these bounds to the map
map.fitBounds(bounds);
map.setZoom(map.getBoundsZoomLevel(bounds));
map.setCenter(beachMarker.getPosition());
}
}
}
}
Don't mix up geocoder an places.
Nakedcherry Waxing Boutique 6th Street Parkhurst,South Africa
the bold part of this string obviously isn't a address-component.
Expecting the desired result is as when I would expect to get my location for a query like
Dr.Molle,Berlin,Germany
The result you get by the geocoder is for 6th Street Parkhurst,South Africa, and the result is correct.
When you look for a place use the places-textsearch, the result for the given query will be: -26.1437060,28.0207660

JSF:Javascript google maps API - markers get the same title

Im probably doing something dumb here but I can't figure out why both of my markers end up with the same title. Both markers end up with the correct location from the geocoder and are displayed in separate places.
Before render
function gMapInitialize() {
var myLocs = [<ui:repeat value = "#{LocationBean.locations.address}" var = "loc" varStatus = "loop">
[ "#{loc.name}","#{loc.street}","#{loc.city}","#{loc.state}", "#{loc.zipCode}"]#{!loop.last ? ',' : ''}
</ui:repeat>];
//<![CDATA[
var myOptions = {
center: new google.maps.LatLng(37.212832,-76.750488),
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var geocoder = new google.maps.Geocoder();
for(var i = 0; i < myLocs.length; i++){
var myLoc = myLocs[i];
var geoOptions = {
address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4],
}
geocoder.geocode( geoOptions ,function(results, status){
if(status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: myLoc[0],
zIndex: i
});
}
});
}
}
// ]]>
After Render:
function gMapInitialize() {
var myLocs = [
[ "Richmond","9 North 3rd Street","Richmond","VA", "23219"],
[ "Hampton Roads","632 North Witchduck Road","Virginia Beach","VA", "23462"]
];
//<![CDATA[
var myOptions = {
center: new google.maps.LatLng(37.212832,-76.750488),
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var geocoder = new google.maps.Geocoder();
for(var i = 0; i < myLocs.length; i++){
var myLoc = myLocs[i];
var geoOptions = {
address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4],
}
geocoder.geocode( geoOptions ,function(results, status){
if(status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: myLoc[0],
zIndex: i
});
}
});
}
}
// ]]>
Am I trying to do too much in one loop? I keep hearing something about closure but am new to javascript and know nothing about it.
Ohh yeah: I get the second of the two names on each marker. The markers are in the right position but both are titled "Hampton Roads". So, the right info is being passed to the title, but its as if title of the first is being overwritten with the title of the second.
UPDATE Well, I fixed it and I think I understand a bit more about closure. So mainly the loop keeps looping and by the time the function is called its already at the end. So even in the below, each marker will probably have the same zIndex and I should pass the "i" as well.
for(var i = 0; i < myLocs.length; i++){
var myLoc = myLocs[i];
var geoOptions = {
address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4],
}
geocoder.geocode( geoOptions ,addMarkers(myLoc[0]));
}
function addMarkers(myTitle){
return function(results,status){
if(status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: myTitle,
zIndex: i
});
}
};
}
It's a simple closure issue. myLoc[i] refers to the same entity after the loop ends in both cases. Just wrap it in a function to create a new scope:
for(var i = 0; i < myLocs.length; i++){
(function(num) {
var myLoc = myLocs[num];
var geoOptions = {
address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4],
}
geocoder.geocode( geoOptions ,function(results, status){
if(status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: myLoc[0],
zIndex: num
});
}(i));
}

Google Maps API v3. How to hide markers on map depending on day & time?

Ok, I have a project map that im working on that pulls data from mysql. in my DB I have a column called "weekends" with a value of "0 or 1" The value of "1" will mean to show the marker no matter of the day or time of the week.
For all other markers i need them to hide for example; from Friday 9 pm to Sunday 9pm. Unless they have the value of "1" in the weekend column, then they would show.
Can anyone help me construct this java script function? Any help will be much appreciated.
here is my code:
//Icon Selection
var customIcons = {
Full: {
icon: 'red.png'
},
Partial: {
icon: 'blue.png',
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(26.075287, -80.309029),
zoom: 12,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml2.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var Udf_DSCategory = markers[i].getAttribute("Udf_DSCategory");
var Description = markers[i].getAttribute("Description");
var Udf_DSLimitsTo = markers[i].getAttribute("Udf_DSLimitsTo");
var Udf_DSType = markers[i].getAttribute("Udf_DSType");
var Udf_DSPIONotes = markers[i].getAttribute("Udf_DSPIONotes");
var Udf_DSApprovedBy = markers[i].getAttribute("Udf_DSApprovedBy");
var Udf_DSLimitsOfClosure = markers[i].getAttribute("Udf_DSLimitsOfClosure");
var ProjectName = markers[i].getAttribute("ProjectName");
var Udf_DSDateClosureFrom = markers[i].getAttribute("Udf_DSDateClosureFrom");
var Udf_DSDateClosureTo = markers[i].getAttribute("Udf_DSDateClosureTo");
var weekend = markers[i].getAttribute("weekend");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("UserText1")),
parseFloat(markers[i].getAttribute("BulletinID")));
var html =
"<b> Project Name: </b> " + ProjectName + "<br/>" +"<b> Category: </b> " + Udf_DSCategory + " <br/>" + "<b> Closure Type: </b>" + Udf_DSType + " <br/> <b> Date From: </b> " + Udf_DSDateClosureFrom + " <b>to</b> " + Udf_DSDateClosureTo + " <br/>" + "<b> Road: </b>" + Description + "<br/>" + "<b> Closure Notes: </b>" + Udf_DSPIONotes + "<br/>" + "<b> Closure Approved by: </b>" + Udf_DSApprovedBy ;
var icon = customIcons[Udf_DSType] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
});
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() {}
Regarding to the comment, it would be the best to fetch only the needed markers from the DB.
The query may look like this(there may be a lot of other ways)
SELECT * FROM `yourTable`
WHERE( weekends=1
OR
WEEKDAY(NOW())<4
OR
(WEEKDAY(NOW())=4 AND HOUR(NOW())<18)
OR
(WEEKDAY(NOW())=6 AND HOUR(NOW())>17)
)

Categories

Resources