如何从访问者的当前位置获取方向到我在嵌入式谷歌地图中的位置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从访问者的当前位置获取方向到我在嵌入式谷歌地图中的位置相关的知识,希望对你有一定的参考价值。
我的网站上有一个嵌入式地图,其中包含指向我办公室地址的标记点。但是,我需要通过Web浏览器中的地理位置自动向用户显示从当前位置到我办公室位置的路线。可能吗?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Find a route using Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function calculateRoute(from, to) {
// Center initialized to Naples, Italy
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(40.84, 14.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(
directionsRequest,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response
});
}
else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function() {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
$("#from-link, #to-link").click(function(event) {
event.preventDefault();
var addressId = this.id.substring(0, this.id.indexOf("-"));
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
$("#" + addressId).val(results[0].formatted_address);
else
$("#error").append("Unable to retrieve your address<br />");
});
},
function(positionError){
$("#error").append("Error: " + positionError.message + "<br />");
},
{
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
});
});
$("#calculate-route").submit(function(event) {
event.preventDefault();
calculateRoute($("#from").val(), "govandi"));
});
});
</script>
<style type="text/css">
#map {
width: 500px;
height: 400px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Calculate your route</h1>
<form id="calculate-route" name="calculate-route" action="#" method="get">
<label for="from">From:</label>
<input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
<a id="from-link" href="#">Get my position</a>
<br />
<label for="to">To:</label>
<input type="text" id="to" name="to" placeholder="Another address" size="30" />
<a id="to-link" href="#">Get my position</a>
<br />
<input type="submit" />
<input type="reset" />
</form>
<div id="map"></div>
<p id="error"></p>
</body>
</html>
答案
我稍微修改了https://www.sitepoint.com/find-a-route-y中使用-geolocation-and-the-google-maps-api /的代码,使用select html表单从用户位置到设置目的地的旅程规划器。
如果它对任何人都有用。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Find a route using Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function calculateRoute(from, to) {
// Center initialized somewhere near London
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(53, -1),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(
directionsRequest,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response
});
}
else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function() {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
$("#from-link, #to-link").click(function(event) {
event.preventDefault();
var addressId = this.id.substring(0, this.id.indexOf("-"));
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
$("#" + addressId).val(results[0].formatted_address);
else
$("#error").append("Unable to retrieve your address<br />");
});
},
function(positionError){
$("#error").append("Error: " + positionError.message + "<br />");
},
{
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
});
});
$("#calculate-route").submit(function(event) {
event.preventDefault();
calculateRoute($("#from").val(), $("#to").val());
});
});
</script>
<style type="text/css">
#map {
width: 500px;
height: 400px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Calculate your route</h1>
<form id="calculate-route" name="calculate-route" action="#" method="get">
<label for="from">From:</label>
<input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
<a id="from-link" href="#">Get my position</a>
<br />
<label for="to">To:</label>
<select id="to">
<option value="51.5548885,-0.108438">Arsenal's Emirates Stadium</option>
<option value="51.481663,-0.1931505">Chelsea's Stamford Bridge</option>
</select>
<br />
<input type="submit" />
<input type="reset" />
</form>
<div id="map"></div>
<p id="error"></p>
另一答案
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Find a route using Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function calculateRoute(from, to) {
var myLatLng = {lat: 19.056, lng: 72.921};
// Center initialized to Mumbai, India
var myOptions = {
zoom: 10,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(
directionsRequest,
function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response
});
$('.distance-in-km').text(response.routes[0].legs[0].distance.value / 1000 + "km");
alert( response.routes[0].legs[0].distance.value / 1000 + "km" ); // the distance in metres
} else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function () {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
navigator.geolocation.getCurrentPosition(function (position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
calculateRoute(results[0].formatted_address, "govandi");
} else {
var marker = new google.maps.Marker({
position: myLatLng,
title: 'Hello World!'
});
marker.setMap(mapObject);
$("#error").append("Unable to retrieve your address<br />");
}
});
});
calculateRoute($("#from").val(), "govandi");
$("#calculate-route").submit(function (event) {
event.preventDefault();
calculateRoute($("#from").val(), "govandi");
});
$('.verify-location > a').click(function(){
$('.verify-location').hide();
$('#calculate-route').show();
});
});
</script>
<style type="text/css">
#map {
width: 500px;
height: 400px;
margin-top: 10px;
}
#calculate-route {
display: none;
}
.verify-location > a {
cursor: pointer;
color: #FCA2A2;
}
</style>
</head>
<body>
<div class="verify-location">Is the your location incorrect? <a>Click以上是关于如何从访问者的当前位置获取方向到我在嵌入式谷歌地图中的位置的主要内容,如果未能解决你的问题,请参考以下文章
打开android原生谷歌地图应用程序获取从当前位置开始的方向