问题
I have to create a circle around a particular city on a google map so I came up with below code and it works fine.
<!DOCTYPE html>
<html>
<style>
body {
margin: 0;
padding: 0;
font: 12px sans-serif;
}
h1, p {
margin: 0;
padding: 0;
}
#map_div{
width:400px;
height:400px;
margin: 0 auto;
}
#outer {
width:400px;
height:50px;
margin:0 auto;
text-align:center;
}
#outer input[type="text"] {
display: block;
margin: 0 auto;
}
</style>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<div id="outer">
<input type="text" name="location" value="Current Location"><br>
<div id="map_div"></div>
</div>
</body>
<script type="text/javascript">
google.maps.event.addDomListener(window, "load", function () {
myMap();
});
function myMap() {
//add global geocoder
window.geocoder = new google.maps.Geocoder();
var mapCanvas = document.getElementById("map_div");
var mapOptions = { zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP, center: new google.maps.LatLng(33.808678, -117.918921) };
window.map = new google.maps.Map(mapCanvas,mapOptions);
drawCircleAroundCity('ottawa');
}
function drawCircleAroundCity(cityName){
if(!cityName) return;
if(!window.geocoder) throw "Geocoder is not loaded";
window.geocoder.geocode({ 'address': cityName }, function (results, status) {
if (status == 'OK') {
addCircle(results[0].geometry.location, true);
} else {
throw 'Unable to find address: ' + address;
}
});
}
function addCircle(position, recenter){
if(typeof(position) != 'object') return;
if(!window.map) throw "Map is not loaded";
var myCity = new google.maps.Circle({
center: position,
radius: 50000,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.4
});
myCity.setMap(window.map);
if(recenter)
window.map.setCenter(position);
}
</script>
</html>
Problem Statement:
Now I have to find out distance of a particular item from current location and show it just above the Current Location
textbox as shown in this below image. I have below item details in which there is an address of the item. Now can we use the full address of below item and calculate the distance from Current Location
and show it above the textbox shown exactly in below image? For example this is 187.51 km away from
. I am not sure what is the right way to do that.
Here is my working jsfiddle
{
"country": "canada",
"state": "ontario",
"city": "ottawa",
"street": "riverside drive",
"number": "1750",
"postal": "k1g 3t6"
}
回答1:
Use google map's distance API, https://developers.google.com/maps/documentation/distance-matrix/start
来源:https://stackoverflow.com/questions/52014472/how-to-calculate-distance-of-an-item-from-current-location-and-show-it-in-a-text