如果我在名为start和end的文本框中为坐标的lat long值提供坐标并单击提交按钮,则下面的代码工作正常。
<script>
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
当我点击地图中的地点时,我想在文本框中获取坐标。我有通过点击地图获取coodrinates的代码。
google.maps.event.addListener(map, 'click', function (e) {
document.getElementById('latitude').value = e.latLng.lat();
document.getElementById('longitude').value = e.latLng.lng();
});
但是我发现难以将点击开始和结束地接受。 当用户第一次单击地图时,必须填充开始的文本框。当他再次点击时,文本框的结尾必须填充。后来,如果他只想改变终点,我将如何将他的点击映射到对应于结尾的文本框?请帮忙
答案 0 :(得分:0)
如果我假设是正确的,那么当你点击地图时,你想要lat很长,
尝试下面
var map;
var geocoder;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initMap() {
var myOptions = {
center: new google.maps.LatLng(41.85, -85.61),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function(event) {
getLocation(event.latLng);
});
var marker;
function getLocation(location) {
document.getElementById('lat').value=location.lat();
document.getElementById('lng').value=location.lng();
getAddress(location);
}
function getAddress(latLng) {
geocoder.geocode( {'latLng': latLng},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
document.getElementById("address").value = results[0].formatted_address;
}
else {
document.getElementById("address").value = "No results";
}
}
else {
document.getElementById("address").value = status;
}
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
&#13;
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
&#13;
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script><input type="text" id="address" size="30"><br><input type="text" id="lat" size="10"><input type="text" id="lng" size="10">
<div id="map_canvas"></div>
&#13;
我添加了额外的功能,它也会告诉你地址。希望这对你有所帮助!