简体   繁体   中英

Move google maps marker on Places Auto-complete

I currently have a map that displays a marker on the users geolocation. I have a text input field set to Places Auto-complete. When a user searches a city name, a new marker is placed on the location. However, the old gelocation marker remains. I want to delete the old marker or move it so only 1 marker is on the map. How can I do this?

Here is my code:

<html>
<head>
    <script>
    var map;

    function initialize() {
        var mapOptions = {
            zoom: 12
     };
    map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

    // Get GEOLOCATION
    if(navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = new google.maps.LatLng(position.coords.latitude,
                                         position.coords.longitude);

        map.setCenter(pos);
        var marker = new google.maps.Marker({
            position: pos,
            map: map,
            draggable:true
        });
      }, function() {
        handleNoGeolocation(true);
      });
    } else {
      // Browser doesn't support Geolocation
      handleNoGeolocation(false);
    }
    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
      };

      map.setCenter(options.position);

    }

// get places auto-complete when user type in location-text-box
    var input = /** @type {HTMLInputElement} */(
  document.getElementById('location-text-box'));


   var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();
    var marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29),
      draggable:true
    });

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      infowindow.close();
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        return;
      }

 // If the place has a geometry, then present it on a map.
    if (place.geometry.viewport) {
       map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);  // Why 17? Because it looks good.
    }
    marker.setIcon(/** @type {google.maps.Icon} */({
      url: place.icon,
      size: new google.maps.Size(71, 71),
      origin: new google.maps.Point(0, 0),
      anchor: new google.maps.Point(17, 34),
      scaledSize: new google.maps.Size(35, 35)
    }));
    marker.setPosition(place.geometry.location);
    marker.setVisible(true);

    var address = '';
    if (place.address_components) {
        address = [
        (place.address_components[0] && place.address_components[0].short_name || ''),
        (place.address_components[1] && place.address_components[1].short_name || ''),
        (place.address_components[2] && place.address_components[2].short_name || '')
      ].join(' ');
    }

  });



}

google.maps.event.addDomListener(window, 'load', initialize);
        </script>
  </head>
  <body>
        <div>
              <input type="text" id="location-text-box">
              <div id="map-canvas"></div>
        </div>
  </body>
  </html>

Make your marker global, and either hide it or move it to the new location

working code snippet:

 var map; var marker; function initialize() { var mapOptions = { zoom: 12 }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Get GEOLOCATION if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); map.setCenter(pos); marker = new google.maps.Marker({ position: pos, map: map, draggable: true }); }, function() { handleNoGeolocation(true); }); } else { // Browser doesn't support Geolocation handleNoGeolocation(false); } 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 }; map.setCenter(options.position); marker = new google.maps.Marker({ position: options.position, map: map, draggable: true }); } // get places auto-complete when user type in location-text-box var input = /** @type {HTMLInputElement} */ ( document.getElementById('location-text-box')); var autocomplete = new google.maps.places.Autocomplete(input); autocomplete.bindTo('bounds', map); var infowindow = new google.maps.InfoWindow(); marker = new google.maps.Marker({ map: map, anchorPoint: new google.maps.Point(0, -29), draggable: true }); google.maps.event.addListener(autocomplete, 'place_changed', function() { infowindow.close(); marker.setVisible(false); var place = autocomplete.getPlace(); if (!place.geometry) { return; } // If the place has a geometry, then present it on a map. if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(17); // Why 17? Because it looks good. } marker.setIcon( /** @type {google.maps.Icon} */ ({ url: place.icon, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(35, 35) })); marker.setPosition(place.geometry.location); marker.setVisible(true); var address = ''; if (place.address_components) { address = [ (place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '') ].join(' '); } }); } google.maps.event.addDomListener(window, 'load', initialize); 
 html, body, #map-canvas { height: 100%; width: 100%; margin: 0px; padding: 0px } 
 <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script> <div style="height:100%; width:100%"> <input type="text" id="location-text-box" /> <div id="map-canvas"></div> </div> 

File javascript.js

function initialize() {

var mapOptions, map, marker, searchBox, city,
    infoWindow = '',
    addressEl = document.querySelector( '#map-search' ),
    latEl = document.querySelector( '.latitude' ),
    longEl = document.querySelector( '.longitude' ),
    element = document.getElementById( 'map-canvas' );
city = document.querySelector( '.reg-input-city' );

mapOptions = {
    // How far the maps zooms in.
    zoom: 8,
    // Current Lat and Long position of the pin/
    center: new google.maps.LatLng( 23.0224, 72.5751 ),
    // center : {
    //  lat: -34.397,
    //  lng: 150.644
    // },
    disableDefaultUI: false, // Disables the controls like zoom control on the map if set to true
    scrollWheel: true, // If set to false disables the scrolling on the map.
    draggable: true, // If set to false , you cannot move the map around.
    // mapTypeId: google.maps.MapTypeId.HYBRID, // If set to HYBRID its between sat and ROADMAP, Can be set to SATELLITE as well.
    // maxZoom: 11, // Wont allow you to zoom more than this
    // minZoom: 9  // Wont allow you to go more up.

};

/**
 * Creates the map using google function google.maps.Map() by passing the id of canvas and
 * mapOptions object that we just created above as its parameters.
 *
 */
// Create an object map with the constructor function Map()
map = new google.maps.Map( element, mapOptions ); // Till this like of code it loads up the map.

/**
 * Creates the marker on the map
 *
 */
marker = new google.maps.Marker({
    position: mapOptions.center,
    map: map,

    draggable: true
});

/**
 * Creates a search box
 */
searchBox = new google.maps.places.SearchBox( addressEl );

/**
 * When the place is changed on search box, it takes the marker to the searched location.
 */
google.maps.event.addListener( searchBox, 'places_changed', function () {
    var places = searchBox.getPlaces(),
        bounds = new google.maps.LatLngBounds(),
        i, place, lat, long, resultArray,
        addresss = places[0].formatted_address;

    for( i = 0; place = places[i]; i++ ) {
        bounds.extend( place.geometry.location );
        marker.setPosition( place.geometry.location );  // Set marker position new.
    }

    map.fitBounds( bounds );  // Fit to the bound
    map.setZoom( 15 ); // This function sets the zoom to 15, meaning zooms to level 15.
    // console.log( map.getZoom() );

    lat = marker.getPosition().lat();
    long = marker.getPosition().lng();
    latEl.value = lat;
    longEl.value = long;

    resultArray =  places[0].address_components;

    // Get the city and set the city input value to the one selected
    for( var i = 0; i < resultArray.length; i++ ) {
        if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
            citi = resultArray[ i ].long_name;
            city.value = citi;
        }
    }

    // Closes the previous info window if it already exists
    if ( infoWindow ) {
        infoWindow.close();
    }
    /**
     * Creates the info Window at the top of the marker
     */
    infoWindow = new google.maps.InfoWindow({
        content: addresss
    });

    infoWindow.open( map, marker );
} );


/**
 * Finds the new position of the marker when the marker is dragged.
 */
google.maps.event.addListener( marker, "dragend", function ( event ) {
    var lat, long, address, resultArray, citi;

    console.log( 'i am dragged' );
    lat = marker.getPosition().lat();
    long = marker.getPosition().lng();

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { latLng: marker.getPosition() }, function ( result, status ) {
        if ( 'OK' === status ) {  // This line can also be written like if ( status == google.maps.GeocoderStatus.OK ) {
            address = result[0].formatted_address;
            resultArray =  result[0].address_components;

            // Get the city and set the city input value to the one selected
            for( var i = 0; i < resultArray.length; i++ ) {
                if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
                    citi = resultArray[ i ].long_name;
                    console.log( citi );
                    city.value = citi;
                }
            }
            addressEl.value = address;
            latEl.value = lat;
            longEl.value = long;

        } else {
            console.log( 'Geocode was not successful for the following reason: ' + status );
        }

        // Closes the previous info window if it already exists
        if ( infoWindow ) {
            infoWindow.close();
        }

        /**
         * Creates the info Window at the top of the marker
         */
        infoWindow = new google.maps.InfoWindow({
            content: address
        });

        infoWindow.open( map, marker );
    } );
});}

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