谷歌地图分页中的重复值

时间:2016-05-19 09:30:01

标签: javascript jquery google-maps jquery-mobile

下面的代码显示地图并在UL中显示结果。我有2个按钮,显示火车站和购物中心。最初,它会正确显示结果,但如果我点击另一个按钮,它将显示重复的值。

的Javascript

                  var map;
                  var pos;
                  var distance;
                  var distancearray = [];
                  var markers = [];
            //=================================================================     

            function initialize() {

                  googleMapsLoaded = false; 

                    map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 13  
                    });

                    // Try HTML5 geolocation
              if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {

                            pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

                        var request = {
                              location:pos,
                              radius:3000, //3000 Meters
                              type:initialtype

                  };

                          infowindow = new google.maps.InfoWindow();
                          var service = new google.maps.places.PlacesService(map);
                          service.nearbySearch(request,callback);

                                infowindow = new google.maps.InfoWindow({
                                map: map,
                                position: pos,
                                content: 'You Are Here',

                              });      
                                  map.setCenter(pos);
                                }, function() {
                                  handleNoGeolocation(true);
                                });
                              } else {
                                // Browser doesn't support Geolocation
                                handleNoGeolocation(false);
                              }

                                function callback(results, status) {

                              if (status !== google.maps.places.PlacesServiceStatus.OK) {

                                   return;
                                }

                              else{ 

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

                                  markers.push(createMarker(results[i]));

                            }

                                            } //end callback function


                                /* listen to the tilesloaded event
                               if that is triggered, google maps is loaded successfully for sure */
                                google.maps.event.addListener(map, 'tilesloaded', function() {
                               googleMapsLoaded = true;
                             //  document.getElementById("mapnotification").innerHTML = "Map Loaded!";
                               $("#mapnotification").hide();
                               $("#map-loaded").show();
                               $("#map-loaded").css('visibility', 'hidden');
                               $("#map-notloaded").hide();
                               //clear the listener, we only need it once
                               google.maps.event.clearListeners(map, 'tilesloaded');
                            });
                            setTimeout(function() {
                              if (!googleMapsLoaded) {
                                 //we have waited 7 secs, google maps is not loaded yet
                                 document.getElementById("mapnotification").innerHTML = "Map NOT Loaded! Make sure you have stable internet connnection";
                                $("#mapnotification").hide();
                                $("#map-notloaded").show();
                                $("#map-loaded").hide();
                              }    
                            }, 7000); 

            function createMarker(place) { // Create Marker and the Icon of the marker
                        //    var bounds = new google.maps.LatLngBounds();
                        var markerlat;
                        var markerlon;  
                        var p2;
                        var output="";

                              var placesList = document.getElementById('places');

                              placeLoc = place.geometry.location;

                              var marker = new google.maps.Marker({
                                map: map,
                                position: place.geometry.location,

                                 icon: {
                                    path: google.maps.SymbolPath.CIRCLE,
                                    scale: 8,
                                    fillColor:'00a14b',
                                    fillOpacity:0.3,
                                    fillStroke: '00a14b',       
                                    strokeWeight:4,
                                    strokeOpacity: 0.7
                                },  // end icon 

                              }); //end of marker variable 

                                markerlat = marker.getPosition().lat()
                                markerlon = marker.getPosition().lng()

                                console.log("Markers Lat" + markerlat);
                                console.log("Markers Lon" + markerlon );


                                p2 = new google.maps.LatLng(markerlat, markerlon);

                                distance = [calcDistance(pos, p2)];

                                //calculates distance between two points in km's
                                function calcDistance(p1, p2) {

                            return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
                                }
                                  distancearray.push([distance, place.name]);
                                  distancearray.sort();
                                  console.log("distancearraylength" + distancearray.length);
                               console.log("Summary" + distancearray);

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

                                     output += '<li>' + distancearray[i][1] + " " + distancearray[i][0]+ " " + "km" + '</li>';
                                     placesList.innerHTML = output;

                                }

                              google.maps.event.addListener(marker, 'click', function() {  //show place name when marker clicked
                                infowindow.setContent(place.name);
                                infowindow.open(map, marker);                       

                              }); // end of marker show place name    
                            }  // end createMarker function

                    function handleNoGeolocation(errorFlag) {
                              if (errorFlag) {
                                var content = 'Error: The Geolocation service failed.';
                              } else {
                                var content = 'Error: Your browser doesn\'t support geolocation.';
                              }

                              var options = {
                                map: map,
                                position: new google.maps.LatLng(60, 105),
                                content: content
                              };

                              var infowindow = new google.maps.InfoWindow(options);
                              map.setCenter(options.position);

                            } // End handleNoGeolocation function


                                  } //End function initialize

                //==========================================================================================================//

                 $(document).on('pagebeforeshow','#itemPanel2', function(e, data){ // Loading of Nearest Place Options

                           bindchoicesclick();

                    function bindchoicesclick(){               

                        $("#subway_station").on("click",function(){
                            //  alert("subway");
                                markers = [];
                                 pos="";
                                 while(distancearray.length > 0) {
                                        distancearray.pop();
                                        }
                                 while(markers.length > 0) {
                                        markers.pop();
                                        }
                                //$("#places").empty();

                                initialtype = ['subway_station'];
                                buttonholder = "Nearest Station";
                                $("#find").val(buttonholder);
                                $("#find").button("refresh");

                                initialize();
                            });

                        $("#shopping_mall").on("click",function(){
                            //  alert("stores");
                             markers = [];
                                pos="";
                              while(distancearray.length > 0) {
                                        distancearray.pop();
                                        }
                                         while(markers.length > 0) {
                                        markers.pop();
                                        }
                            //  distancearray.splice(0).
                             // $("#places").empty();
                                initialtype = ['shopping_mall'];
                                buttonholder = "Nearest Mall";
                                $("#find").val(buttonholder);
                                $("#find").button("refresh");

                                initialize();

                            });
     }  
      });    

HTML

    <h1 id="headerField">Nearby Search</h1>

        </div>

                     <a href="#globa_map" class="ui-btn" id="subway_station">Search Nearest Train Station</a>
                     <a href="#globa_map" class="ui-btn" id="shopping_mall">Search Nearest Mall</a>


            </div>   
            <!--Train Stations -->
                <div id="globa_map" data-role="page">
                  <div data-role="header">
                    <a href="#" data-transition="slide" data-rel="back" data-icon="arrow-l">Back</a>
                    <a href="#" data-role="button" id="maprefresh" data-mini="true" data-icon="refresh" data-inline="true"class="ui-btn-right">Refresh</a>
                        <h1 id="headerField">Global</h1>
             </div>

                     <div data-role="content">  
                    <!-- <input type="button" id="refreshmap" value="Refresh">       -->     
                    <p id="mapnotification">Please wait while the map is loading...</p>
                    <p id="map-loaded">Map Loaded!</p>
                    <p id="map-notloaded">Map NOT Loaded! Make sure you have stable internet connnection</p>
                    <h2>Results</h2>
                    <ul id="places"></ul>
                    <button id="more">More results</button>

                     <div id="map" style="height:400px;">

                          </div>                     
            </div>

0 个答案:

没有答案