我正在尝试向我的定向 Google 地图添加其他标记(自定义图标),但我似乎无法在 initialize() 函数之外添加这些标记。
我需要将它们添加到 initialize() 函数之外,因为我想根据路线更改图标。这是我遇到麻烦的添加额外标记测试。脚本的所有其余部分都可以完美运行。
非常感谢您的帮助。
到目前为止的代码:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var stepDisplay;
function initialize() {
var latlng = new google.maps.LatLng( <? echo $lat; ?> , <? echo $lon; ?> );
var rendererOptions = {draggable: true};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var myOptions = {zoom: 14,center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP,mapTypeControl: false};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
//计算路由
function calcRoute() {
var travelMode = 'DRIVING';
var start = $("#routeStart").val();
var via = $("#routeVia2").val();
var end = $("#routeVia").val();
var waypoints = [];
if (via != '') {waypoints.push({location: via,stopover: true});
}
var request = {
origin: start,
destination: end,
waypoints: waypoints,
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: google.maps.DirectionsTravelMode[travelMode]
};
//显示路线并将 LATLNG 传递给 PHP 文件以供进一步处理
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myRoute = response.routes[0];
var txtDir = '';
for (var i=0; i<myRoute.legs[0].steps.length; i++) {
txtDir += myRoute.legs[0].steps[i].path+"";
}
var strLAT = "" + txtDir;
//发送数据到 URL PHP 文件
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}}
xmlHttp.open("POST",'MYPHPFILE',true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("LATLON="+strLAT);
//警报测试以确保 PHP 正确处理数据
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
alert($('#ResponseDiv').text());
}
添加额外标记测试
var wxlatlng = new google.maps.LatLng( 52 , -1 );
var marker = new google.maps.Marker({
position: wxlatlng,
map: map,
icon: "http://nwsgeo.com/demo/images/pins/road-closed.jpg",
title: "test icon",
});
//错误信息
}else{
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
}else if(status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
}else{
alert("There was an unknown error in your request. Requeststatus: nn" + status);
}}});}