谷歌距离地图,从给定地址/Lat,Lng 和自定义标记的最短路径,一个是默认选择当前位置,一个是自定义
Posted
技术标签:
【中文标题】谷歌距离地图,从给定地址/Lat,Lng 和自定义标记的最短路径,一个是默认选择当前位置,一个是自定义【英文标题】:Google Distance Map with Shortest Path from given address/Lat,Lng and customise marker, One is default pick current location and one is customise 【发布时间】:2021-10-21 17:00:28 【问题描述】:我对谷歌距离地图有疑问,我们有多个位置,我想从给定的多个地址绘制从我当前位置到最近地址的地图,我已经创建并且它工作正常,但是我有地图问题标记,默认情况下它的返回标记点地址,但我希望当前位置返回默认当前位置地址,我只想自定义目标标记,当我使用“suppressMarkers:true”目标标记自定义工作但当前位置标记不返回默认当前位置时,当我使用“suppressMarkers:false”时,两个标记都返回默认地址/位置。
<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>
【问题讨论】:
【参考方案1】:根据我们的理解,您应该对当前格式化的地址使用“地理编码”。
如果您将使用“suppressMarkers: true”,在这种情况下,您必须手动设置标记。使用目标标记自定义没有问题,但只有开始/起点标记的问题。
因此,您应该相应地自定义目标标记,并使用地理编码获取当前位置 formated_address 并将其设置在您的原始标记中。
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);
);
);
完整示例:
<!doctype html>
<html lang="en">
<head>
<title>Google maps</title>
<style>
.subheading,.sidelinks,.timify-widget-open-buttondisplay:none!important
.map-containerbox-shadow:0 0 0 2px #ccc;transition:300ms;display:flex;position:relative;overflow:hidden
.map-container inputposition:absolute;top:0;left:0;opacity:0;width:0
.map-boxmin-width:calc(100% - 200px);max-width:calc(100% - 200px);min-height:320px;height:calc(100vh - 340px);transition:300ms
.city-boxlist-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 lipadding: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.activecolor:#fff;background-color:black!important
.city-box li:nth-child(even)background-color:#eee
.map-labelposition: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::beforecontent:'';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-labelright:0
.map-container input:checked ~ .map-label::beforetransform:rotate(225deg);margin-left:5px
.map-container input:checked ~ .map-boxwidth:100%;min-width:100%!important;max-width:100%!important
.map-container input:checked ~ .city-boxright:-200px
#floating-panelposition: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_contentdisplay:flex;width:100%;max-width:350px;align-items:center
.info_content .media-thumb imgmax-width:100px;margin-right:10px
.info_content .contentdisplay:inline-block
.info_content h3margin:0 0 4px 0;font-size:15px
.info_content pmargin:0;font-size:12px;line-height:1.5
.scroller::-webkit-scrollbarheight:12px;width:5px;background:#333
.scroller::-webkit-scrollbar-thumbbackground:#969494;-webkit-border-radius:1ex;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.75)
.scroller::-webkit-scrollbar-cornerbackground:#333
.scrolleroverflow-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>
根据屏幕截图位置,“勒克瑙”是您的默认/原始位置,带有默认标记,位置“Gurugram”是您的自定义(标记)位置
【讨论】:
以上是关于谷歌距离地图,从给定地址/Lat,Lng 和自定义标记的最短路径,一个是默认选择当前位置,一个是自定义的主要内容,如果未能解决你的问题,请参考以下文章