gpt4 book ai didi

javascript - 如何在谷歌地图上显示方向后隐藏其他标记

转载 作者:行者123 更新时间:2023-12-03 01:42:11 26 4
gpt4 key购买 nike

此 Google map 用于获取前往由客户坐标指定的位置作为目的地的路线。

为了从选择中的数据中获取该值,我将其设为 google.maps.LatLng 对象,并将坐标保存为值中的字符串,然后解析出纬度和经度创建 LatLng 对象。

步骤是:

1-将坐标保存在选项值中:

for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}

2-解析这些坐标并在路线请求中创建一个 google.maps.LatLng 对象:

function calculateRoute() {

var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
// ....

(以上所有工作正常)

-----这就是我陷入困境的地方:-----

即使显示了到指定标记的方向,问题是所有标记仍在 map 中,对我来说,我尝试让我的函数仅显示两件事:方向和我选择的代码客户端的标记,所有其他标记将隐藏。

这是我关于在代码中添加的内容的注释,

**1--***一旦我添加此函数即可将所有标记推送到一个变量中*

    makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', function(data) {

for (var i = 0; i < data.length; i++) {

var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].Latitude, data[i].Longitude),
title: data[i].CodeClient,
map: map
});

gmarkers.push(marker);
}

});

**2--***我添加此功能来隐藏其他标记*

 function toggleMarkers() {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);
else gmarkers[i].setMap(map);
}
}

这个问题我已经面对好几天了,似乎无法解决,即使我尝试在此处和 Google Maps API 文档中查看各种代码块,但仍然无法弄清楚如何解决隐藏其他标记。

任何建议、想法和帮助将不胜感激!

这是屏幕截图:

enter image description here

-------------------------------------------------------- -------------------------------------------------- ------------------------------------------------

这是我更新后的代码

根据您的建议,这是我的代码的更新。

效果很好,在我单击按钮(清除标记)后,所有标记都会删除。

现在我想知道如何创建函数 toggleMarkers() ,删除所有标记,但它会将标记保留在我选择的代码客户端中,

var gmarkers = [];

var map;
var directionsService;
var directionsDisplay;
var geocoder;
var infowindow;

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function init() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();

/*++++++++++++++++++*/

var mapOptions = {
zoom: 6,
center: center = new google.maps.LatLng(32, -6),
mapTypeId: google.maps.MapTypeId.ROADMAP
}

/*++++++++++++++++++*/

map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions_panel'));

// Detect user location
if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(function(position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': userLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('start').value = results[0].formatted_address
}
});

}, function() {
alert('Geolocation is supported, but it failed');
});
}

/*++++++++++++++++++*/

makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', function(data) {

var data = JSON.parse(data.responseText);
var selectBox = document.getElementById('destination');

for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}

});


}

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function toggleMarkers() {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);
else gmarkers[i].setMap(map);
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

function addOption(selectBox, text, value) {
var option = document.createElement("OPTION");
option.text = text;
option.value = value;
selectBox.options.add(option);
}

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
var hakim = document.getElementById('destination');
console.log("selected option value=" + destination);
console.log(" value=" + hakim);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}

var request = {
origin: start,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
console.log("origin:" + start);
console.log("dest:" + destination.toUrlValue(12));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
alert("???");
displayLocation(hakim);
}

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/


function displayLocation(rythmstu_innotec) {
var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
'<br />Latitude : ' + rythmstu_innotec.Latitude +
'<br />Longitude : ' + rythmstu_innotec.Longitude +
'<br />Route : ' + rythmstu_innotec.Route +
'<br />Secteur : ' + rythmstu_innotec.Secteur +
'<br />Agence : ' + rythmstu_innotec.Agence +
'<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
'<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
'<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
'<br />Téléphone : ' + rythmstu_innotec.Tel +
'<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
'<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
'<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
'<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
'<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
'<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';

if (parseInt(rythmstu_innotec.Latitude) == 0) {
geocoder.geocode({
'GeoAdresse': rythmstu_innotec.GeoAdresse
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.rythmstu_innotec,
title: rythmstu_innotec.name
});

google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: rythmstu_innotec.name
});
gmarkers.push(marker);

google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
body {
font: normal 14px Verdana;
}

h1 {
font-size: 24px;
}

h2 {
font-size: 18px;
}

#sidebar {
float: right;
width: 30%;
}

#main {
padding-right: 15px;
}

.infoWindow {
width: 220px;
}
<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>

<body onload="init();">



<form id="services">
Location: <input type="text" id="start" value="Midar" /> Destination:
<select id="destination" onchange="calculateRoute();"></select>
<input type="button" value="clear map" onclick="toggleMarkers();" />
</form>

<section id="sidebar">
<div id="directions_panel"></div>
</section>

<section id="main">
<div id="map_canvas" style="width: 70%; height: 750px;"></div>
</section>

</body>

最佳答案

您永远不会调用 toggleMarkers 函数。

  1. 修改为hideMarkers:
function hideMarkers() {
for (i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
}
  • 然后在成功时在路线服务回调函数中调用它:
  • function calculateRoute() {
    var start = document.getElementById('start').value;
    var destination = document.getElementById('destination').value;
    var hakim = document.getElementById('destination');
    var destPt = destination.split(",");
    var destination = new google.maps.LatLng(destPt[0], destPt[1]);
    if (start == '') {
    start = center;
    }

    var request = {
    origin: start,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    hideMarkers(); // <========================= call it here
    }
    });
    displayLocation(hakim);
    }

    代码片段:

    var gmarkers = [];

    var map;
    var directionsService;
    var directionsDisplay;
    var geocoder;
    var infowindow;

    /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
    function init() {
    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    infowindow = new google.maps.InfoWindow();

    /*++++++++++++++++++*/

    var mapOptions = {
    zoom: 6,
    center: center = new google.maps.LatLng(32, -6),
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    /*++++++++++++++++++*/

    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions_panel'));

    // Detect user location
    if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(function(position) {
    var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    geocoder.geocode({
    'latLng': userLocation
    }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
    document.getElementById('start').value = results[0].formatted_address
    }
    });

    }, function() {
    alert('Geolocation is supported, but it failed');
    });
    }

    /*++++++++++++++++++*/

    makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', function(data) {

    var data = JSON.parse(data.responseText);
    var selectBox = document.getElementById('destination');

    for (var i = 0; i < data.length; i++) {
    displayLocation(data[i]);
    addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
    }
    });
    }
    /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
    function hideMarkers() {
    console.log("gmarkers.length=" + gmarkers.length);
    for (i = 0; i < gmarkers.length; i++) {
    gmarkers[i].setMap(null);
    }
    }
    /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

    function addOption(selectBox, text, value) {
    var option = document.createElement("OPTION");
    option.text = text;
    option.value = value;
    selectBox.options.add(option);
    }
    /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

    function calculateRoute() {
    var start = document.getElementById('start').value;
    var destination = document.getElementById('destination').value;
    var hakim = document.getElementById('destination');
    console.log("selected option value=" + destination);
    console.log(" value=" + hakim);
    var destPt = destination.split(",");
    var destination = new google.maps.LatLng(destPt[0], destPt[1]);
    if (start == '') {
    start = center;
    }

    var request = {
    origin: start,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    console.log("origin:" + start);
    console.log("dest:" + destination.toUrlValue(12));
    directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    hideMarkers();
    }
    });
    displayLocation(hakim);
    }

    /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

    function makeRequest(url, callback) {
    var request;
    if (window.XMLHttpRequest) {
    request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
    } else {
    request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
    }
    request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
    callback(request);
    }
    }
    request.open("GET", url, true);
    request.send();
    }

    /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/


    function displayLocation(rythmstu_innotec) {
    var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
    '<br />Latitude : ' + rythmstu_innotec.Latitude +
    '<br />Longitude : ' + rythmstu_innotec.Longitude +
    '<br />Route : ' + rythmstu_innotec.Route +
    '<br />Secteur : ' + rythmstu_innotec.Secteur +
    '<br />Agence : ' + rythmstu_innotec.Agence +
    '<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
    '<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
    '<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
    '<br />Téléphone : ' + rythmstu_innotec.Tel +
    '<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
    '<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
    '<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
    '<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
    '<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
    '<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';

    if (parseInt(rythmstu_innotec.Latitude) == 0) {
    geocoder.geocode({
    'GeoAdresse': rythmstu_innotec.GeoAdresse
    }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
    var marker = new google.maps.Marker({
    map: map,
    position: results[0].geometry.rythmstu_innotec,
    title: rythmstu_innotec.name
    });

    google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(content);
    infowindow.open(map, marker);
    });
    }
    });
    } else {
    var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
    var marker = new google.maps.Marker({
    map: map,
    position: position,
    title: rythmstu_innotec.name
    });
    gmarkers.push(marker);

    google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(content);
    infowindow.open(map, marker);
    });
    }
    }
    body {
    font: normal 14px Verdana;
    }

    h1 {
    font-size: 24px;
    }

    h2 {
    font-size: 18px;
    }

    #sidebar {
    float: right;
    width: 30%;
    }

    #main {
    padding-right: 15px;
    }

    .infoWindow {
    width: 220px;
    }
    <title>MAP itinéraire </title>
    <meta charset="utf-8">
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>

    <body onload="init();">

    <form id="services">
    Location: <input type="text" id="start" value="Midar" /> Destination:
    <select id="destination" onchange="calculateRoute();"></select>
    <input type="button" value="clear map" onclick="toggleMarkers();" />
    </form>

    <section id="sidebar">
    <div id="directions_panel"></div>
    </section>

    <section id="main">
    <div id="map_canvas" style="width: 70%; height: 750px;"></div>
    </section>

    </body>

    关于javascript - 如何在谷歌地图上显示方向后隐藏其他标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50789561/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com