我必须在谷歌地图上围绕特定城市创建一个圆圈,所以我想出了下面的代码并且它工作正常。
<!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>
问题陈述:
现在我必须找出特定元素与当前位置的距离,并将其显示在 Current Location
文本框上方,如下图所示。我有以下元素详细信息,其中有元素的地址。现在我们可以使用下面元素的完整地址并计算与 Current Location
的距离并将其显示在下图中显示的文本框上方吗?例如,距离
187.51 公里。我不确定这样做的正确方法是什么。
这是我的工作 jsfiddle
{
"country": "canada",
"state": "ontario",
"city": "ottawa",
"street": "riverside drive",
"number": "1750",
"postal": "k1g 3t6"
}
最佳答案
关于javascript - 如何计算元素与当前位置的距离并将其显示在文本中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52014472/