如何获得排序的字母标记 [英] How to get Sorted alphabetical markers

查看:115
本文介绍了如何获得排序的字母标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的小提琴中的代码有3个固定位置。然后可以输入一个地址,并计算从该地址到所有三个固定位置的距离。然后按照右侧边栏中的距离按顺序对结果进行排序。



我试图弄清楚如何为每个结果指定字母标记。所以每次计算结果时,第一个最接近的标记将是字母A,第二个最接近的标记将是字母B,以此类推。我还想让字母A出现在第一个最接近的结果旁边的边栏中,而字母B出现在边栏中第二个最接近的结果旁边等等。



<我没有找到任何指示如何做到这一点?任何人都可以帮忙吗?

谢谢

http://jsfiddle.net/geocodezip/vj0cpv0c/2/

  var locations = [
[John Doe,145 Rock Ridge Road,Chester,NY,41.314926,-74.270134,http://maps.google.com/mapfiles/ms/ Jim Smith,12 Williams Rd,Montvale,NJ,41.041599,-74.019554,http://maps.google.com/mapfiles/ms/ John Jones,689 Fern St Township of Washington,NJ,40.997704,-74.050598,http://maps.google.com/mapfiles/ms /icons/yellow.png],


解决方案

我使用通用的JavaScript来做出最接近的匹配结果,可能有更好的方法来使用API​​。



添加代码:

  var pins = []; 

results.forEach(function(result){
closest.forEach(function(addr){
if(result.address === addr.address){
pins.push(addr);
}
});
});

并且在for循环中使用了针脚[i]而不是最接近的。



所有代码:

var locations = [[John Doe,29 Buhl Lane, NY,40.858924,-73.297327,http://maps.google.com/mapfiles/ms/icons/blue.png],[Jim Smith,Williamsville,Montvale,NJ, 41.041599,-74.019554,http://maps.google.com/mapfiles/ms/icons/green.png],[John Jones,689 Fern St Township of Washington,NJ,40.997704, - 74.050598,http://maps.google.com/mapfiles/ms/icons/yellow.png\"],// alert(locations.length); var geocoder = null; var map = null; var customerMarker = null; var gmarkers = []; var closest = []; var directionsDisplay = new google.maps.DirectionsRenderer();; var directionsService = new google.maps.DirectionsService(); var map; function initialize(){// alert (在里面); geocoder = new google.maps.Geocoder(); map = new google.maps.Map(document.getElementById('map'),{zoom:9,center:new google.maps.LatLng(52.6699927,-0.7274620),mapTypeId:google.maps.MapTypeId.ROADMAP}); var infowindow = new google.maps.InfoWindow(); var marker,i; var bounds = new google.maps.LatLngBounds(); document.getElementById('info')。innerHTML =found+ locations.length +locations< br>; for(i = 0; i< locations.length; i ++){var coordStr = locations [i] [2]; var coords = coordStr.split(,); var pt = new google.maps.LatLng(parseFloat(coords [0]),parseFloat(coords [1])); bounds.extend(PT); marker = new google.maps.Marker({position:pt,map:map,icon:locations [i] [3],address:locations [i] [1],title:locations [i] [0],html:位置[i] [0] +< br>+ locations [i] [1] +< br>< br>< a href ='javascript:getDirections(customerMarker.getPosition() + locations [i] [1] +& quot;);'>获取路线< / a>}); gmarkers.push(标记); google.maps.event.addListener(marker,'click',(function(marker,i){return function(){infowindow.setContent(marker.html); infowindow.open(map,marker);}})(marker , 一世)); } map.fitBounds(bounds); $(#mdiv)。click(function(){$(#side_bar)。css({z-index:100,top:0px}); $(#panel) .css(z-index,-100); $(#mdiv)。css(display,none);})} function codeAddress(){var address = document.getElementById('address' )。值; geocoder.geocode({'address':address},function(results,status){if(status == google.maps.GeocoderStatus.OK){map.setCenter(results [0] .geometry.location); if(customerMarker )customerMarker.setMap(null); customerMarker = new google.maps.Marker({map:map,position:results [0] .geometry.location}); nearest = findClosestN(results [0] .geometry.location,12) ; //获取驾驶距离nearest = nearest.splice(0,12); calculateDistances(results [0] .geometry.location,nearest,12);} else {alert('Geocode由于以下原因不成功:'+状态);}});}函数findClosestN(pt,numberOfResults){var closest = []; document.getElementById('info')。innerHTML + =processing+ gmarkers.length +< br>; for(var i = 0; i

  html,body,#map {margin:0;填充:0; height:600px;宽度:400px; } .text {width:300px; height:600px;背景颜色:白色;溢出:滚动;溢出-y:auto; overflow-x:hidden; } #side_bar {z-index:100;位置:绝对;顶部:135px; left:400px; } #panel {z-index:-100;显示:块;位置:绝对;顶部:135px; left:400px; } #mdiv {z-index:500;宽度:25px;身高:25px;显示:无;背景颜色:红色;边框:1px纯黑色;位置:绝对;左:660px;顶部:112px; } .mdiv {height:25px; width:2px; margin-left:12px;背景颜色:黑色;转换:旋转(45度); -ms-transform:rotate(45deg); / * IE 9 * / -webkit-transform:rotate(45deg); / * Safari和Chrome * / z-index:1; } .md {height:25px; width:2px;背景颜色:黑色;转换:旋转(90deg); -ms-transform:rotate(90deg); / * IE 9 * / -webkit-transform:rotate(90deg); / * Safari和Chrome * / z-index:2; } tr:nth-​​child(even){background:#CCC} tr:nth-​​child(odd){background:#FFF}  

 < div class =bh-sl-container> < div id =page-header> < h1 class =bh-sl-title>审核员定位器< / h1> < / DIV> < div class =bh-sl-form-container> < form id =bh-sl-user-locationmethod =postaction =#> < div class =form-input> < label for =bh-sl-address>输入地址或邮编:< / label> < input id =addresstype =textvalue =Danbury,CT/> < input type =buttonvalue =Submitonclick =codeAddress(); /> < / DIV> < /形式> < / DIV> < table border =0style =height:100%> < tr style =height:100%> < td style =height:100%> < div id =map>< / div> < / TD> < TD> < div id =side_barclass ='text'>< / div> < div id =panelclass ='text'>< / div> < / TD> < / TR> < /表> < div id =info>< / div> < div id =mdiv> < div class =mdiv> < div class =md> < / DIV> < / DIV> < / div>  


The code in the fiddle below has 3 Fixed Locations. An address can then be inputted and the distance from that address to all three Fixed Locations will be calculated. The results are then sorted in order by distance in a sidebar on the right.

I'm trying to figure out how to assign lettered markers for each result. So each time the results are calculated, the first closest marker would be letter A, the second closest marker would be letter B and so on. I'd also like the letter A to appear in the sidebar next to the first closest result and letter B to appear in the sidebar next to the second closest results and so on.

I haven't been able to find any instructions how to do this? Can anyone help?

Thanks

http://jsfiddle.net/geocodezip/vj0cpv0c/2/

var locations = [
  ["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],

解决方案

To follow up,sorted pins I used general javascript to make closest match results, there may be a better way of doing this with the API.

added code:

 var pins = [];     

 results.forEach(function(result){
    closest.forEach(function (addr){    
        if(result.address === addr.address){         
        pins.push(addr);
      }
    });
 }); 

and used pins[i] instead of closest in the for loop.

all code:

 var locations = [
  ["John Doe", "29 Buhl Lane, East Northport, NY ", "40.858924, -73.297327", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],

];
// alert(locations.length);

var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  // alert("init");
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 9,
    center: new google.maps.LatLng(52.6699927, -0.7274620),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var infowindow = new google.maps.InfoWindow();
  var marker, i;
  var bounds = new google.maps.LatLngBounds();
  document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
  for (i = 0; i < locations.length; i++) {
    var coordStr = locations[i][2];
    var coords = coordStr.split(",");
    var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
    bounds.extend(pt);
    marker = new google.maps.Marker({
      position: pt,
      map: map,
      icon: locations[i][3],
      address: locations[i][1],
      title: locations[i][0],
      html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + locations[i][1] + "&quot;);'>Get Directions</a>"
    });
    gmarkers.push(marker);
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(marker.html);
          infowindow.open(map, marker);
        }
      })
      (marker, i));
  }
  map.fitBounds(bounds);

  $("#mdiv").click(function() {
    $("#side_bar").css({
      "z-index": 100,
      "top": "0px"
    });
    $("#panel").css("z-index", -100);
    $("#mdiv").css("display", "none");
  })

}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      if (customerMarker) customerMarker.setMap(null);
      customerMarker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      closest = findClosestN(results[0].geometry.location, 12);
      // get driving distance
      closest = closest.splice(0, 12);
      calculateDistances(results[0].geometry.location, closest, 12);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function findClosestN(pt, numberOfResults) {
  var closest = [];
  document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
  for (var i = 0; i < gmarkers.length; i++) {
    gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
    document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
    gmarkers[i].setMap(null);
    closest.push(gmarkers[i]);
    closest.sort(sortByDist);
  }

  return closest;
}

function sortByDist(a, b) {
  return (a.distance - b.distance)

}

function calculateDistances(pt, closest, numberOfResults) {
  var service = new google.maps.DistanceMatrixService();
  var request = {
    origins: [pt],
    destinations: [],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    avoidHighways: false,
    avoidTolls: false
  };
  for (var i = 0; i < closest.length; i++) {
    request.destinations.push(closest[i].getPosition());
  }
  service.getDistanceMatrix(request, function(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('side_bar');
      outputDiv.innerHTML = '';
			
      var results = response.rows[0].elements;
      // save title and address in record for sorting
      for (var i = 0; i < closest.length; i++) {
        results[i].title = closest[i].title;
        results[i].address = closest[i].address;
        results[i].idx_closestMark = i;
      }
      
     results.sort(sortByDistDM);    
     
     var pins = [];     
      		
     results.forEach(function(result){
        closest.forEach(function (addr){    
        	if(result.address === addr.address){         
          	pins.push(addr);
          }
        });
     });      
    
      for (var i = 0;
        ((i < numberOfResults) && (i < closest.length)); i++) {
        pins[i].setMap(map);       
        var letterMarkers = String.fromCharCode(97 + i);
        pins[i].set('label', letterMarkers);
        outputDiv.innerHTML += letterMarkers + " <br><a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + results[i].address + "&quot;);'>Get Directions</a><br><hr>"
        
    
      }
    }
  });
}

function getDirections(origin, destination) {
  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setMap(map);
      directionsDisplay.setDirections(response);
      $("#side_bar").css({
        "z-index": -100,
        "top": "25px"
      });
      $("#panel").css("z-index", 100);
      $("#mdiv").css("display", "block");

      directionsDisplay.setPanel(document.getElementById('panel'));


    }
  });
}

function sortByDistDM(a, b) {
  return (a.distance.value - b.distance.value)
}

google.maps.event.addDomListener(window, 'load', initialize);

 html,
 body,
 #map {
   margin: 0;
   padding: 0;
   height: 600px;
   width: 400px;
 }
 
 .text {
   width: 300px;
   height: 600px;
   background-color: white;
   overflow: scroll;
   overflow-y: auto;
   overflow-x: hidden;
 }
 
 #side_bar {
   z-index: 100;
   position: absolute;
   top: 135px;
   left: 400px;
 }
 
 #panel {
   z-index: -100;
   display: block;
   position: absolute;
   top: 135px;
   left: 400px;
 }
 
 #mdiv {
   z-index: 500;
   width: 25px;
   height: 25px;
   display: none;
   background-color: red;
   border: 1px solid black;
   position: absolute;
   left: 660px;
   top: 112px;
 }
 
 .mdiv {
   height: 25px;
   width: 2px;
   margin-left: 12px;
   background-color: black;
   transform: rotate(45deg);
   -ms-transform: rotate(45deg);
   /* IE 9 */
   -webkit-transform: rotate(45deg);
   /* Safari and Chrome */
   z-index: 1;
 }
 
 .md {
   height: 25px;
   width: 2px;
   background-color: black;
   transform: rotate(90deg);
   -ms-transform: rotate(90deg);
   /* IE 9 */
   -webkit-transform: rotate(90deg);
   /* Safari and Chrome */
   z-index: 2;
 }
 
 tr:nth-child(even) {
   background: #CCC
 }
 
 tr:nth-child(odd) {
   background: #FFF
 }

<div class="bh-sl-container">
  <div id="page-header">
    <h1 class="bh-sl-title">The Auditor Locator</h1>

  </div>

  <div class="bh-sl-form-container">
    <form id="bh-sl-user-location" method="post" action="#">
      <div class="form-input">
        <label for="bh-sl-address">Enter Address or Zip Code:</label>
        <input id="address" type="text" value="Danbury, CT" />
        <input type="button" value="Submit" onclick="codeAddress();" />
      </div>
    </form>
  </div>

  <table border="0" style="height:100%">
    <tr style="height:100%">
      <td style="height:100%">
        <div id="map"></div>
      </td>
      <td>
        <div id="side_bar" class='text'></div>
        <div id="panel" class='text'></div>
      </td>
    </tr>
  </table>


  <div id="info"></div>
  <div id="mdiv">
    <div class="mdiv">
      <div class="md">
      </div>
    </div>
  </div>

这篇关于如何获得排序的字母标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆