【问题标题】:Move google maps marker on Places Auto-complete在地方自动完成上移动谷歌地图标记
【发布时间】:2015-04-08 12:18:03
【问题描述】:

我目前有一张在用户地理位置上显示标记的地图。我有一个文本输入字段设置为 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>

【问题讨论】:

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


【解决方案1】:

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

工作代码sn-p:

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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 1970-01-01
      • 2013-04-25
      • 2017-07-09
      • 1970-01-01
      • 2016-11-17
      • 2018-01-26
      • 1970-01-01
      相关资源
      最近更新 更多