我想做的是onclick
谷歌地图。尝试创建包含地址的数组。问题是当我警告数组时它只显示当前值。
我也试过waypts.length
了,它只提醒1。这意味着当我点击谷歌地图时数组值被替换。那么问题似乎是什么?
代码:
function initialize() {
var geocoder = new google.maps.Geocoder();
var waypts=[];
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
var input=e.latLng;
var lat = parseFloat(input.lat());
var lng = parseFloat(input.lng());
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add=results[0].formatted_address;
waypts.push({
location:add,
stopover:true
});
var lngth=waypts.length;
alert(JSON.stringify(waypts));
}
});
<!-- ************** for route between markers ******************* -->
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true, //false it if you want a marker from the direction service
polylineOptions: {
strokeColor: 'green', //"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var lngth=waypts.length;
var start = waypts[0][0];//"Bopal, Ahmedabad, Gujarat, India";
var end = waypts[waypts.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";
//remove start destination from array
var a=waypts.shift();
//remove end destination from array
waypts.pop();
var request = {
origin:start,
destination:end,
waypoints:waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
提前致谢。