Reputation: 139
I have a issue with google distance map, we have multiple locations and i want to drew map from my current location to nearest address from given multiple address and i have already created and its working fine, but i have a issue with map marker, by default its return marker point address but i want current location return default current position address and i want to customise only destination marker, when i use "suppressMarkers: true" destination marker customisation working but current position marker not return default current location, and when i use "suppressMarkers: false" both marker return default address/locations.
<script type="text/javascript">
var map,
currentPosition,
directionsDisplay,
directionsService,
destinationLatitude = 67.38,
destinationLongitude = -56.11;
jQuery(document).ready(function( $ ) {
getLocation();
});
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function getPosition(position) {
localStorage.setItem("current_latitude", position.coords.latitude);
localStorage.setItem("current_longitude", position.coords.longitude);
locSuccess(position.coords.latitude,position.coords.longitude);
}
function initializeMapAndCalculateRoute(lat, lon)
{
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
currentPosition = new google.maps.LatLng(lat, lon);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 16,
center: currentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
var currentPositionMarker = new google.maps.Marker({
position: currentPosition,
map: map,
title: "My Location"
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(currentPositionMarker, 'click', function() {
infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon);
infowindow.open(map, currentPositionMarker);
});
calculateRoute(destinationLatitude, destinationLongitude);
}
function locSuccess(latitude,longitude) {
initializeMapAndCalculateRoute(latitude,longitude);
}
function calculateRoute(targetLat, targetLon) {
var targetDestination = new google.maps.LatLng(targetLat, targetLon);
if (currentPosition != '' && targetDestination != '') {
var request = {
origin: currentPosition,
destination: targetDestination,
travelMode: google.maps.DirectionsTravelMode["DRIVING"]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setPanel(document.getElementById("directions"));
directionsDisplay.setDirections(response);
$("#outputs").show();
}
else {
$("#outputs").hide();
}
});
}
else {
$("#outputs").hide();
}
}
</script>
Upvotes: 2
Views: 172
Reputation: 1809
As per our understanding, you should use "geocode" for the current formatted address.
If you will use "suppressMarkers: true", in that case, you have to set the marker manually. Use have no issue with destination marker customization but the issue with only starting/origin marker.
So you should customize the destination marker accordingly and by using geocode get the current location formated_address and set it within your origin marker.
google.maps.event.addListener(currentPositionMarker, "click", function()
{
var point = currentPositionMarker.getPosition();
map.panTo(point);
MapGeocoder.geocode({
'latLng': currentPositionMarker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, currentPositionMarker);
}
});
});
Full Example:
<!doctype html>
<html lang="en">
<head>
<title>Google maps</title>
<style>
.subheading,.sidelinks,.timify-widget-open-button{display:none!important}
.map-container{box-shadow:0 0 0 2px #ccc;transition:300ms;display:flex;position:relative;overflow:hidden}
.map-container input{position:absolute;top:0;left:0;opacity:0;width:0}
.map-box{min-width:calc(100% - 200px);max-width:calc(100% - 200px);min-height:320px;height:calc(100vh - 340px);transition:300ms}
.city-box{list-style-type:none;padding:10px 0;width:200px;height:100%;right:0;position:absolute;margin:0;box-sizing:border-box;transition:300ms;overflow:hidden;overflow-y:auto}
.city-box li{padding:12px 12px 12px 36px;cursor:pointer;background-image:url(https://developers.google.com/maps/documentation/javascript/images/marker_greenA.png);background-repeat:no-repeat;background-size:25px auto;background-position:10px;transition:350ms}
.city-box li.active{color:#fff;background-color:black!important}
.city-box li:nth-child(even){background-color:#eee}
.map-label{position:absolute;width:24px;height:60px;right:200px;top:calc(50% - 30px);background-color:#fff;box-shadow:-3px 0 3px #cccc;z-index:2;border-radius:4px 0 0 4px;cursor:pointer;transition:300ms;display:flex;justify-content:center;align-items:center}
.map-label::before{content:'';width:10px;height:10px;margin-left:-2px;border-top:2px solid currentColor;border-right:2px solid currentColor;transform:rotate(45deg)}
.map-container input:checked ~ .map-label{right:0}
.map-container input:checked ~ .map-label::before{transform:rotate(225deg);margin-left:5px}
.map-container input:checked ~ .map-box{width:100%;min-width:100%!important;max-width:100%!important}
.map-container input:checked ~ .city-box{right:-200px}
#floating-panel{position:absolute;top:10px;left:25%;z-index:5;background-color:#fff;padding:5px;border:1px solid #999;text-align:center;font-family:"Roboto","sans-serif";line-height:30px;padding-left:10px}
.info_content{display:flex;width:100%;max-width:350px;align-items:center}
.info_content .media-thumb img{max-width:100px;margin-right:10px}
.info_content .content{display:inline-block}
.info_content h3{margin:0 0 4px 0;font-size:15px}
.info_content p{margin:0;font-size:12px;line-height:1.5}
.scroller::-webkit-scrollbar{height:12px;width:5px;background:#333}
.scroller::-webkit-scrollbar-thumb{background:#969494;-webkit-border-radius:1ex;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.75)}
.scroller::-webkit-scrollbar-corner{background:#333}
.scroller{overflow-y:scroll;scrollbar-color:#333 #969494;scrollbar-width:thin!important}
</style>
</head>
<body>
<div class="container-fluid px-0 map-container">
<div id="floating-panel">
<b>Mode of Travel: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
<input type="checkbox" id="maptoggle">
<label for="maptoggle" class="map-label maptogglemenu"></label>
<div class="map-box" id="map_canvas"></div>
<ul id="mybranches" class="city-box">
<li class="active" data-lan="28.38" data-lon="77.12" data-title="Location Title" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Delhi, India</li>
<li data-lan="12.120000" data-lon="76.680000" data-title="Location Title A" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Nanjangud, Mysore, Karnataka</li>
<li data-lan="24.879999" data-lon="74.629997" data-title="Location Title B" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Chittorgarh, Rajasthan</li>
<li data-lan="16.994444" data-lon="73.300003" data-title="Location Title C" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Ratnagiri, Maharashtra</li>
<li data-lan="19.155001" data-lon="72.849998" data-title="Location Title D" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Goregaon, Mumbai, Maharashtra</li>
<li data-lan="24.794500" data-lon="73.055000" data-title="Location Title E" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Pindwara, Rajasthan</li>
<li data-lan="21.250000" data-lon="81.629997" data-title="Location Title F" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Raipur, Chhattisgarh</li>
<li data-lan="16.166700" data-lon="74.833298" data-title="Location Title G" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Gokak, Karnataka</li>
<li data-lan="19.076090" data-lon="72.877426" data-title="Location Title H" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Mumbai, Maharashtra</li>
<li data-lan="14.167040" data-lon="75.040298" data-title="Location Title I" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Sagar, Karnataka</li>
<li data-lan="26.540457" data-lon="88.719391" data-title="Location Title J" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Jalpaiguri, West Bengal</li>
<li data-lan="24.633568" data-lon="87.849251" data-title="Location Title K" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Pakur, Jharkhand</li>
</ul>
</div>
<div id="results" style="display:none;">
<div id="directions" class="scroller px-3" style="overflow: hidden; overflow-y: auto; max-height: 300px;"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_map_api_key_here&sensor=false&libraries=geometry&v=3"></script>
<script type="text/javascript">
var map,
currentPosition,
targetPosition,
targetMarker,
infowindow,
currentLatitude,
currentLongitude,
directionsDisplay,
directionsService,
locationTitle,
locationAddress,
destinationLatitude = 49.4505682,
destinationLongitude = 11.0702432;
jQuery(document).ready(function( $ ) {
if (!localStorage.getItem("current_latitude")) {
getLocation();
}
else{
currentLatitude = localStorage.getItem("current_latitude");
currentLongitude = localStorage.getItem("current_longitude");
locSuccess(currentLatitude, currentLongitude);
}
});
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function getPosition(position) {
currentLatitude = position.coords.latitude;
currentLongitude = position.coords.longitude;
localStorage.setItem("current_latitude", currentLatitude);
localStorage.setItem("current_longitude", currentLongitude);
locSuccess(currentLongitude,currentLongitude);
}
function locSuccess(currentLatitude,currentLongitude) {
var nearestLocation = null;
var locations = [];
jQuery('ul#mybranches li').each(function(){
var location_lat = jQuery(this).attr('data-lan');
var location_lng = jQuery(this).attr('data-lon');
var location_title = jQuery(this).attr('data-title');
var location_address = jQuery(this).attr('data-html');
var location_image = jQuery(this).attr('data-img');
var p1 = new google.maps.LatLng(currentLatitude, currentLongitude);
var p2 = new google.maps.LatLng(location_lat, location_lng);
var distance = calcDistance(p1, p2) * 1000;
if ((distance * 1000) > 0) {
if (nearestLocation === null || nearestLocation.distance > distance) {
nearestLocation = {distance: location_image, mylat: currentLatitude, mylng: currentLongitude, location_lat: location_lat, location_lng: location_lng, location_title: location_title, location_address: location_address, location_image: location_image };
}
}
});
var lat = nearestLocation.location_lat;
var long = nearestLocation.location_lng;
var title = nearestLocation.location_title;
var address = nearestLocation.location_address;
var image = nearestLocation.location_image;
jQuery('#mybranches li[data-lan]').removeClass('active');
jQuery('#mybranches li[data-title="'+title+'"]').addClass('active');
initializeMapAndCalculateRoute(currentLatitude,currentLongitude,lat,long,title,address,image);
}
function initializeMapAndCalculateRoute(lat, lon, destinationLatitude, destinationLongitude, locationTitle, locationAddress,locationImage)
{
currentPosition = new google.maps.LatLng(lat, lon);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 15,
center: currentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
MapGeocoder = new google.maps.Geocoder();
var rendererOptions = {
map: map,
suppressMarkers: true
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(map);
var currentPositionMarker = new google.maps.Marker({
position: currentPosition,
map: map,
title: "Current position"
});
infowindow = new google.maps.InfoWindow({ map: map });
google.maps.event.addListener(currentPositionMarker, "click", function() {
var point = currentPositionMarker.getPosition();
map.panTo(point);
MapGeocoder.geocode({
'latLng': currentPositionMarker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, currentPositionMarker);
}
});
});
document.getElementById("mode").addEventListener("change", () => {
calculateRoute(destinationLatitude, destinationLongitude, locationTitle, locationAddress,locationImage);
});
// calculate Route
calculateRoute(destinationLatitude, destinationLongitude, locationTitle, locationAddress,locationImage);
}
function calculateRoute(targetLat, targetLon, locationTitle, locationAddress, locationImage) {
const targetDestination = new google.maps.LatLng(targetLat, targetLon);
const selectedMode = document.getElementById("mode").value ? document.getElementById("mode").value : 'DRIVING';
if (currentPosition != '' && targetDestination != '') {
const request = {
origin: currentPosition,
destination: targetDestination,
travelMode: google.maps.TravelMode[selectedMode],
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
createMarker(targetDestination, locationTitle, locationAddress, locationImage);
directionsDisplay.setPanel(document.getElementById("directions"));
directionsDisplay.setDirections(response);
jQuery("#results").show();
}
else {
jQuery("#results").hide();
}
});
}
else {
jQuery("#results").hide();
}
}
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
function createMarker(latlng, label, html, image) {
var contentString = '<div class="info_content">' +
'<div class="media-thumb"><img src="'+image+'"/></div>' +
'<div class="content">'+
'<h3>'+label+'</h3>' +
'<p>'+html+'</p>' +
'</div>'+
'</div>';
targetMarker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
icon: 'https://developers.google.com/maps/documentation/javascript/images/marker_greenA.png',
zIndex: Math.round(latlng.lat() * -100000) << 5
});
targetMarker.myname = label;
google.maps.event.addListener(targetMarker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, targetMarker);
});
return targetMarker;
}
function clearMarkers() {
targetMarker.setMap(null);
}
jQuery(document).on('click', 'li[data-lan]', function () {
if(!currentLatitude || !currentLongitude){
currentLatitude = localStorage.getItem("current_latitude");
currentLongitude = localStorage.getItem("current_longitude");
}
jQuery('li[data-lan]').removeClass('active');
jQuery(this).addClass('active');
destinationLatitude = jQuery(this).attr('data-lan');
destinationLongitude = jQuery(this).attr('data-lon');
locationTitle = jQuery(this).attr('data-title');
locationAddress = jQuery(this).attr('data-html');
locationImage = jQuery(this).attr('data-img');
clearMarkers();
calculateRoute(destinationLatitude,destinationLongitude,locationTitle,locationAddress,locationImage);
});
jQuery(document).ready(function( $ ) {
if(localStorage.getItem('distancemapmenu') && localStorage.getItem('distancemapmenu') == 'checked'){
jQuery('#maptoggle').prop("checked", true);
}
});
jQuery(document).on('click', '.maptogglemenu', function(){
if(jQuery('#maptoggle').is(':checked')){
var value = '';
}else{
var value = 'checked';
}
localStorage.setItem('distancemapmenu', value);
});
</script>
</body>
</html>
As per screenshot Location, "Lucknow" is your default/origin location with default marker and location "Gurugram" is your customize(marker) location
Upvotes: 1