Google API to map nearby properties in Salesforce - google-maps

I asked this question originally in the Salesforce StackExchange, but was redirected here, since it's more of a Google API question than a Salesforce question.
Right now I have the following code, which creates a marker at the location of the property on a visualforce page that has an embedded Google Map. When the user clicks on the marker, an info window appears with information on the property.
<apex:page standardController="Property__c">
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
</script>
<style>
#map {
font-family: Arial;
font-size: 12px;
line-height: normal !important;
height: 800px;
background: transparent;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</apex:page>
This is working just fine. But I am trying to modify it to also show properties nearby to this property. I have gotten as far as using an SOQL query to find these properties, pass their addresses into an array, geocode these addresses and set a marker at each geocoordinate. All of that works just swell.
Where I've been stuck, is in displaying the infowindow that appears when the user clicks one of these markers. Not only can I not create an infowindow for the NEW markers, but the infowindow for the OLD "main" marker is breaking as well. In fact, even if I comment the infowindow and listener events for the new markers, the original is still broken. These infowindows need to display different information than the infowindow for the "main" marker. Here is my modified code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy = 0; <
apex: repeat value = "{!getgeoList}"
var = "m" >
geos[idy++] = "{!m}"; <
/apex:repeat>
for (var i = 0; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map
});
addIinfo(marker2, html);
}
function addInfo(marker2, html) {
var infowindow2 = new google.maps.InfoWindow({
content: html
});
marker2.addListener(marker2, 'click', function() {
infowindow2.open(marker2.get('map'), marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});

I changed marker2.addListener to google.maps.event.addListener. This worked, except that my original marker was showing the same information as the marker2 markers. When I changed the marker2 icon to blue, I realized that this was because it was putting a marker2 marker over the original marker. So I changed i = 0 to i=1 in my for loop, and now my code works just great! :)
Here is my new code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy=0;
<apex:repeat value="{!getgeoList}" var="m">
geos[idy++]="{!m}";
</apex:repeat>
for (var i = 1; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
addInfo(marker2,html);
}
function addInfo(marker2,html) {
var infowindow2 = new google.maps.InfoWindow({
content: html });
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});

Related

Google Maps Nearby Search (Show Selected nearby markers only with autocomplete )

I have this code, which works fine, but there is just one issue which I am getting:
When we search nearby places, it appends the new nearby search markers with the old markers, screenshots are attached in these links.
Here I have searched the nearby banks:
http://prntscr.com/aouxra
It has successfully shown, but now if I search another nearby place like hotel, it will append its markers with the banks markers which has been searched previously, like this:
http://prntscr.com/aouz23
I want to only show the markers of the autocompleted nearby search query only.
function getNearby(lat,lng,map){
var availableTags = [
"hotel",
"bank",
"atm",
"school",
];
$( "#nearby" ).autocomplete({
source: availableTags,
select: function (event, ui) {
var request = null;
request = {
location: {lat:lat, lng:lng},
radius: 5500,
types: [ui.item.value]
};
var service = null;
var infowindow = null;
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
//var markers = [];
var markers = [];
var bounds = map.getBounds()
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++)
{
createMarker(results[i]);
//alert(results)
}
}
}
function createMarker(place) {
//markers.push(place);
var marker = '';
var placeLoc = '';
placeLoc = place.geometry.location;
marker = new google.maps.Marker({
map: map,
position: placeLoc
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
alert(markers.length);
}
});
}
function getLocation() {
$("#myNearby").css('display', 'block');
$("#directions").css('display', 'none');
$("#map").css('display', 'none');
$("#panel").css('display', 'none');
$("#load").css('display', 'none');
$("#googleMap").css('display', 'block');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
setLocationValue(position.coords.latitude,position.coords.longitude);
//getCurrentLocationValue(position.coords.latitude,position.coords.longitude);
var mapProp = {
center:new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myMarker = new google.maps.Marker({
position: {lat:position.coords.latitude, lng:position.coords.longitude},
animation:google.maps.Animation.BOUNCE
});
myMarker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"You are Located in Lat: "+position.coords.latitude+' Lng: '+position.coords.longitude
});
infowindow.open(map,myMarker);
getNearby(position.coords.latitude,position.coords.longitude,map);
<?php /*?>$("#myNearby a").click(function(){
//alert('Working');
var request = {
location: {lat:position.coords.latitude, lng:position.coords.longitude},
radius: 5500,
types: [$("#location").val()]
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
});<?php */?>
}
function setLocationValue(lat,lng){
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
//console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
itemLocality = address_component.address_components[0].long_name;
//console.log("City: " + address_component.address_components[0].long_name + itemLocality);
$("#location").val(itemLocality);
}
});
}
else{
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
});
}
Remove the existing markers from the map before showing the new ones. Make the markers array global, then do this at the beginning of getNearby:
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
markers = [];

How to drag marker and click to set at the same time in Google Maps API v3?

I'm new in Google Maps API v3, I'm trying to add click event listener to re-set the marker, but I want have the posibility to drag the marker too.
Actually I only can drag the marker, this is my code:
var lat = null;
var lng = null;
var map = null;
var geocoder = null;
var marker = null;
jQuery(document).ready(function(){
lat = jQuery('#lat').val();
lng = jQuery('#long').val();
jQuery('#pasar').click(function(){
codeAddress();
return false;
});
initialize();
});
function initialize() {
geocoder = new google.maps.Geocoder();
if(lat !='' && lng != '')
{
var latLng = new google.maps.LatLng(lat,lng);
}
else
{
var latLng = new google.maps.LatLng(11.027113, -63.862023);
}
var myOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true
});
updatePosition(latLng);
}
function codeAddress() {
var address = document.getElementById("direccion").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
updatePosition(results[0].geometry.location);
google.maps.event.addListener(marker, 'dragend', function(){
updatePosition(marker.getPosition());
});
} else {
alert("No podemos encontrar la direccion, error: " + status);
}
});
}
function updatePosition(latLng)
{
jQuery('#lat').val(latLng.lat());
jQuery('#long').val(latLng.lng());
}
I tried to add the following code:
myListener = google.maps.event.addListener(map, 'click', function(event) {
if(marker){marker.setMap(null)}
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
But it does not work.
I want to place the marker with both options, dragging and click. How I can achieve that in my code?
Thanks!
There is no placeMarker function in your code, and not sure why you only want the marker placed on the first click on the map (you are removing the listener after that). This is what I think you want:
var lat = null;
var lng = null;
var map = null;
var geocoder = null;
var marker = null;
var myListener = null;
jQuery(document).ready(function() {
lat = jQuery('#lat').val();
lng = jQuery('#long').val();
jQuery('#pasar').click(function() {
codeAddress();
return false;
});
initialize();
});
function initialize() {
geocoder = new google.maps.Geocoder();
if (lat != '' && lng != '') {
var latLng = new google.maps.LatLng(lat, lng);
} else {
var latLng = new google.maps.LatLng(11.027113, -63.862023);
}
var myOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function() {
updatePosition(marker.getPosition());
});
updatePosition(latLng);
google.maps.event.addListener(map, 'click', function(event) {
if (marker) {
marker.setPosition(event.latLng)
} else {
marker = new google.maps.Marker({
map: map,
position: event.latLng,
draggable: true
});
}
updatePosition(event.latLng);
});
}
function codeAddress() {
var address = document.getElementById("direccion").value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
updatePosition(results[0].geometry.location);
google.maps.event.addListener(marker, 'dragend', function() {
updatePosition(marker.getPosition());
});
} else {
alert("No podemos encontrar la direccion, error: " + status);
}
});
}
function updatePosition(latLng) {
jQuery('#lat').val(latLng.lat());
jQuery('#long').val(latLng.lng());
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="lat" value="42" />
<input id="long" value="-85" />
<input id="pasar" type="button" value="geocode" />
<input id="direccion" value="New York, NY" />
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

Google Places API - Adding Places Details

I have the following code:
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(start,showError);
}
else{
error('Geo Location is not supported');
}
}
function start(position) {
var mySearch = document.getElementById("search").value;
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng,
zoom: 12
});
var request = {
location: latlng,
radius: 500,
query: mySearch
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name, place.website);
infowindow.open(map, this);
});
}
The code works fine however I am trying to retrieve more details about a place. I know about the place details at: https://developers.google.com/maps/documentation/javascript/places#place_details I'm just unsure where and how to adjust my code to say add in the places website. I'm struggling to work out where to get the reference and then how to use it. If someone could write it within my code that would be great.
Adjusted "createMarker" function (not tested):
function createMarker(place) {
var placeLoc = place.geometry.location;
if (place.icon) {
var image = new google.maps.MarkerImage(
place.icon, new google.maps.Size(71, 71),
new google.maps.Point(0, 0), new google.maps.Point(17, 34),
new google.maps.Size(25, 25));
} else var image = null;
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
contentStr += '<br>'+place.types+'</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
}
working example

Google Maps API v3 multiple markers Infowindow

I've used the code below to display a map with multiple markers and infowindows. Now I have encountered the very common problem of the last infowindow showing up on all markers. I've tried all sorts of solutions including: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/ and this one http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop but none of them fix the problem.
Here is my code:
var infowindow = null;
var geocoder;
var map;
$(document).ready(function() {
initialize();
});
function initialize() {
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, people);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
var people = [
{"userid":"47","lastname":"lastname1","firstname":"firstname1","address":"Paris, France","phone1":"00000000000","phone2":"","email":"me#me.com"},
{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"Versaille, France","phone1":"0","phone2":"0","email":"me#me.com"}
];
function setMarkers(map, people) {
for (var i = 0; i < people.length; i++) {
var p = people[i];
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
geocoding is an asynchronous request. So when you use geocoding inside the for-loop, the loop is already finished when you receive the results, i will always be 1 and point to the last item of people.
What you can do: split the marker-creation into 2 functions. 1 for the loop which calls the 2nd function that creates the markers:
remove the current function setMarkers and add the following 2 functions to your script:
function setMarkers(map,people) {
for (var i = 0; i < people.length; i++) {
setMarker(map, people[i])
}
}
function setMarker(map, people) {
var p=people;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The rest of your script may stay as it is.

Question about Google Map get direction service V3

I want to use Direction service of google map for my website. Since I use it first time, I don't know how to start with it. One good example code that is exactly what I want is here:
Direction example
When I download it and run in my browser (any browser) for getting deal with it, map is rendered only a moment and then goes away! I don't know why?!
And second Question: Is there any such example that you know?
Thanks a lot in advance
To draw route on map click on map two times so route created on two that points
var map;
var infowindow = new google.maps.InfoWindow();
var wayA;
var wayB;
var geocoder = new google.maps.Geocoder();
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
panel: document.getElementById('right-panel'),
draggable: true
});
var directionsService = new google.maps.DirectionsService();
var data = {};
initMap();
function initMap() {
debugger;
map = new google.maps.Map(document.getElementById('rmap'), {
center: new google.maps.LatLng(23.030357, 72.517845),
zoom: 15
});
google.maps.event.addListener(map, "click", function (event) {
if (!wayA) {
wayA = new google.maps.Marker({
position: event.latLng,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000"
});
// calculateAndDisplayRoute(directionsService, directionsDisplay, wayA, wayB);
} else {
if (!wayB) {
debugger;
wayB = new google.maps.Marker({
position: event.latLng,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=E|FF0000|000000"
});
calculateAndDisplayRoute(directionsService, directionsDisplay, wayA, wayB);
}
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
return total;
}
function computeTotalDuration(result) {
var total = 0;
var myroute = result.routes[0].legs[0].duration.text;
return myroute;
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, wayA, wayB) {
debugger;
directionsDisplay.setMap(map);
// directionsDisplay.setPanel(document.getElementById('dvPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
debugger;
calculateAndDisplayRoute(directionsService, directionsDisplay.getDirections(), wayA, wayB);
});
directionsService.route({
origin: wayA.getPosition(),
destination: wayB.getPosition(),
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function (response, status) {
if (status === 'OK') {
debugger;
var route = response.routes[0];
wayA.setMap(null);
wayB.setMap(null);
pinA = new google.maps.Marker({
position: route.legs[0].start_location,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000"
}),
pinB = new google.maps.Marker({
position: route.legs[0].end_location,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=E|FF0000|000000"
});
google.maps.event.addListener(pinA, 'click', function () {
infowindow.setContent("<b>Route Start Address = </b>" + route.legs[0].start_address + " <br/>" + route.legs[0].start_location);
infowindow.open(map, this);
});
google.maps.event.addListener(pinB, 'click', function () {
debugger;
infowindow.setContent("<b>Route End Address = </b>" + route.legs[0].end_address + " <br/><b>Distance=</b> " + computeTotalDistance(directionsDisplay.getDirections()) + " Km <br/><b>Travel time=</b> " + computeTotalDuration(directionsDisplay.getDirections()) + " <br/> " + route.legs[0].end_location);
infowindow.open(map, this);
});
} else {
window.alert('Directions request failed due to ' + status);
}
directionsDisplay.setDirections(response);
});
}