在地方自动完成上移动谷歌地图标记

时间:2015-02-08 19:19:53

标签: javascript google-maps google-maps-api-3 google-places-api google-geolocation

我目前有一张地图,显示用户地理位置的标记。我有一个文本输入字段设置为Places Auto-complete。当用户搜索城市名称时,会在该位置上放置新标记。然而,旧的凝胶标记仍然存在。我想删除旧标记或移动它,因此地图上只有1个标记。我怎么能这样做?

这是我的代码:

<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>

2 个答案:

答案 0 :(得分:14)

使您的标记全局,并将其隐藏或移动到新位置

工作代码段:

&#13;
&#13;
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);
&#13;
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

文件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 );
    } );
});}