-1

I have this code, which works fine, but there is just one issue which I am getting:

When we search nearby places, it appends the new nearby search markers with the old markers, screenshots are attached in these links.

Here I have searched the nearby banks: http://prntscr.com/aouxra

It has successfully shown, but now if I search another nearby place like hotel, it will append its markers with the banks markers which has been searched previously, like this:

http://prntscr.com/aouz23

I want to only show the markers of the autocompleted nearby search query only.

    function getNearby(lat,lng,map){

            var availableTags = [
            "hotel",
            "bank",
            "atm",
            "school",
            ];
            $( "#nearby" ).autocomplete({
                source: availableTags,
                select: function (event, ui) {              

                var request = null;

                request = {
                    location: {lat:lat, lng:lng},
                    radius: 5500,
                    types: [ui.item.value]
                };

                var service = null;
                var infowindow = null;

                infowindow = new google.maps.InfoWindow();

                service = new google.maps.places.PlacesService(map);

                service.nearbySearch(request, callback);

                //var markers = [];

                var markers = [];
                var bounds = map.getBounds()
                function callback(results, status) {


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


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

                        createMarker(results[i]);

                        //alert(results)
                    }
                }
                }



                function createMarker(place) {

                    //markers.push(place);

                    var marker = '';
                    var placeLoc = '';

                    placeLoc = place.geometry.location;

                    marker = new google.maps.Marker({
                    map: map,
                    position: placeLoc
                    });

                    markers.push(marker);

                    google.maps.event.addListener(marker, 'click', function() {
                    infowindow.setContent(place.name);
                    infowindow.open(map, this);
                    });



                }

                 alert(markers.length);


                }
            });
    }   


    function getLocation() {

        $("#myNearby").css('display', 'block'); 

        $("#directions").css('display', 'none'); 

        $("#map").css('display', 'none'); 

        $("#panel").css('display', 'none');

        $("#load").css('display', 'none');

        $("#googleMap").css('display', 'block'); 

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else { 
            alert("Geolocation is not supported by this browser.");
            }
    }

    function showPosition(position) {

         setLocationValue(position.coords.latitude,position.coords.longitude);
         //getCurrentLocationValue(position.coords.latitude,position.coords.longitude);

         var mapProp = {
         center:new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
         zoom:10,
         mapTypeId:google.maps.MapTypeId.ROADMAP
      };


        var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);


        var myMarker = new google.maps.Marker({
        position: {lat:position.coords.latitude, lng:position.coords.longitude},
        animation:google.maps.Animation.BOUNCE
        });

        myMarker.setMap(map);


        var infowindow = new google.maps.InfoWindow({
        content:"You are Located in Lat: "+position.coords.latitude+' Lng: '+position.coords.longitude
        });

        infowindow.open(map,myMarker);

        getNearby(position.coords.latitude,position.coords.longitude,map);

        <?php /*?>$("#myNearby a").click(function(){

            //alert('Working');

            var request = {
            location: {lat:position.coords.latitude, lng:position.coords.longitude},
            radius: 5500,
            types: [$("#location").val()]
            };

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

            function callback(results, status) {
                if (status == google.maps.places.PlacesServiceStatus.OK) {
                    for (var i = 0; i < results.length; i++) {
                        createMarker(results[i]);
                    }
                }
            }

            function createMarker(place) {
                var placeLoc = place.geometry.location;
                var marker = new google.maps.Marker({
                map: map,
                position: place.geometry.location
            });

            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent(place.name);
                infowindow.open(map, this);
            });
            }

        });<?php */?>


    }


    function setLocationValue(lat,lng){

        var latlng = new google.maps.LatLng(lat, lng);

        var geocoder = new google.maps.Geocoder();

        geocoder.geocode({latLng: latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    var arrAddress = results;
                    //console.log(results);
                    $.each(arrAddress, function(i, address_component) {
                    if (address_component.types[0] == "locality") {
                        itemLocality = address_component.address_components[0].long_name;
                        //console.log("City: " + address_component.address_components[0].long_name + itemLocality);
                        $("#location").val(itemLocality);
                    }
                });
            } 
        else{
                alert("No results found");
            }
        } 
        else {
            alert("Geocoder failed due to: " + status);
        }

        });


    }
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • Please provide a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve) that demonstrates the issue (can't execute pictures). – geocodezip Apr 06 '16 at 15:11

1 Answers1

0

Remove the existing markers from the map before showing the new ones. Make the markers array global, then do this at the beginning of getNearby:

for (var i=0; i<markers.length; i++) {
  markers[i].setMap(null);
}
markers = [];
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • I have declared markers = [] ; before callback function of the nearby search and pushing the marker in the array in createMarker function. then checking markers.length just right after createMarker function but gives 0. http://prntscr.com/aovs7s Can you please correct my code and send the full code. If possible, Thanks – Shan Sarfraz Apr 06 '16 at 15:05
  • Is that `markers` array global? (and did you remove all the local versions). What do you mean by "right after createMarker function" when you say you get a length of 0? – geocodezip Apr 06 '16 at 15:14
  • ok in the above code which i have mentioned in the question i have declared global array right before this function, function callback(results, status) { } like this markerArray = []; and in the createMaker function in the above code mentioned in the question pushing markers in the markerArray. but when i try see the using alert(markerArray.length) i get out count as 0. – Shan Sarfraz Apr 06 '16 at 16:23