简体   繁体   中英

Create a new array from the elements that are unique for several arrays

Here is a piece of my code:

            var things = new Object();
            things.location = new Array();
            for (var i = 0; i < clickedMarkers.length; i++) {
                var mark = clickedMarkers[i],
                    markLatitude =  mark.position.lat(),
                    markLongitude =  mark.position.lng();

                things.location.push({
                    'lat': markLatitude,
                    'lng': markLongitude
                });
            }

as a result we have the following pairs:

{lat:53.5412,lng:9.994180000000028},{lat:53.0862838,lng:8.789075099999991},   {lat:53.0738902,lng:8.805211800000052},{lat:53.5412,lng:9.994180000000028},{lat:53.5412,lng:9.994180000000028}

I compare the element of each pair by 'lat', using the following code:

            var arr = {};

            for ( var j=0, len=things.location.length; j < len; j++ )
                arr[things.location[j]['lat']] = things.location[j];

            things.location = new Array();

            for ( var key in arr )
                things.location.push(arr[key]);

But the correct way is to compare that both elements of the pair lat and lng are differ, because for the big array of pairs - lat can be the same, but lng - differ.

How to compare both elements of each pair?

Options:

  1. use the google.maps.LatLng .equals method
  2. use the google.maps.geometry.spherical.computeDistanceBetween method, if the distance is less than some small number (say 1.0 meters), treat them as the same (latitudes and longitudes are floating point numbers, comparing them for equality is problematic).

Based on geocodezip's answer. Used the following code:

  //get all markers for the cluster;
  var clickedMarkers = cluster.getMarkers();

  //get the base point to compare all other markers
  var base = new google.maps.LatLng(clickedMarkers[0].position.lat(), clickedMarkers[0].position.lng());

            var total = 0;
            for (var i = 0; i < clickedMarkers.length; i++) {
                var mark = clickedMarkers[i],
                    markLatitude =  mark.position.lat(),
                    markLongitude =  mark.position.lng();
                var _coordinates =  new google.maps.LatLng(markLatitude,   markLongitude);

                var point = google.maps.geometry.spherical.computeDistanceBetween(_coordinates, base);
                total= total + point;
            }

            console.log('total', total);

            if (total == 0)
           {some action}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM