Как повторно инициализировать карты Google с помощью маркера при нажатии кнопки - PullRequest
0 голосов
/ 06 августа 2020

Я встроил карту с API Карт Google, и она работает нормально. Но я хочу сделать кнопку «Прикрепить мое местоположение» (которую нажимает пользователь), и когда пользователь нажимает эту кнопку, моя карта перезагружается с новым маркером (маркер указывает на широту и долготу пользователя). Я успешно получил широту и долготу пользователя, когда пользователь нажимает кнопку, и теперь, как сделать мою карту загруженной с пользовательской новой широтой и долготой? Ниже мой код:

<script>
function getClicked(latLng) {
console.log(latLng);
}
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {
        lat: start[0],
        lng: start[1]
      },
      zoom: zoom,
      mapTypeId: 'roadmap'
    });

    <?php if (isset($start)) { ?>
      marker = new google.maps.Marker({
        map: map,
        position: {
          lat: start[0],
          lng: start[1]
        }
      });
      marker.addListener('click', function() {
        geocoder.geocode({
          'location': {
            lat: start[0],
            lng: start[1]
          }
        }, function(results, status) {
          if (status === 'OK') {
            if (results[0]) {
              infowindow.setContent(results[0].formatted_address);
              infowindow.open(map, marker);
            } else {
              window.alert('No results found');
            }
          } else {
            window.alert('Geocoder failed due to: ' + status);
          }
        });
      });
    <?php } ?>


    // search box
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // zoom ke search box
    map.addListener('bounds_changed', function() {
      searchBox.setBounds(map.getBounds());
    });

    //popup window
    var geocoder = new google.maps.Geocoder();
    var infowindow = new google.maps.InfoWindow();

    // map diklik
    map.addListener('click', function(e) {

      if (marker != undefined) marker.setMap(null);
      marker = new google.maps.Marker({
        map: map,
        position: e.latLng
      });
      marker.addListener('click', function() {
        geocoder.geocode({
          'location': e.latLng
        }, function(results, status) {
          if (status === 'OK') {
            if (results[0]) {
              infowindow.setContent(results[0].formatted_address);
              infowindow.open(map, marker);
            } else {
              window.alert('No results found');
            }
          } else {
            window.alert('Geocoder failed due to: ' + status);
          }
        });
      });

      getClicked([e.latLng.lat(), e.latLng.lng()])
    });

    // alamat di search
    searchBox.addListener('places_changed', function() {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      if (marker != undefined) marker.setMap(null);

      // For each place, get the icon, name and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        if (!place.geometry) {
          console.log("Returned place contains no geometry");
          return;
        }

        // Create a marker
        marker = new google.maps.Marker({
          map: map,
          title: place.name,
          position: place.geometry.location
        });
        marker.addListener('click', function() {
          geocoder.geocode({
            'location': place.geometry.location
          }, function(results, status) {
            if (status === 'OK') {
              if (results[0]) {
                infowindow.setContent(results[0].formatted_address);
                infowindow.open(map, marker);
              } else {
                window.alert('No results found');
              }
            } else {
              window.alert('Geocoder failed due to: ' + status);
            }
          });
        });

        var latlng = {
          lat: place.geometry.location.lat(),
          lng: place.geometry.location.lng()
        }
        getClicked([place.geometry.location.lat(), place.geometry.location.lng()])

        if (place.geometry.viewport) {
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });

      map.fitBounds(bounds);
    });
  }

  function getClicked(latlng) {
    console.log(latlng)
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap&libraries=places&v=weekly" defer></script>

<script>
let pinMyLocation = document.querySelector('.pin-btn');
pinMyLocation.addEventListener('click', (e) => {
//I have new user latitude and longitude here
//I want to reload map here
});
</script>

1 Ответ

0 голосов
/ 09 августа 2020

Если вы используете sh для изменения исходного местоположения карты, вам понадобится какая-то форма постоянного хранилища - localStorage и cookies кажутся наиболее очевидными, а localStorage предлагает лучший вариант imo.

В приведенном ниже коде используется geolocation, чтобы попытаться определить местоположение пользователя, а кнопка Pin It будет использовать это местоположение для перемещения карты и маркера. В качестве альтернативы, просто щелкнув карту в любом месте, вы также переместите карту и маркер.

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: Locate & Pin</title>
        <style>
            #map{
                width:800px;
                height:600px;
                float:none;
                margin:auto;
            }
        </style>
        <script>
            function initMap(){
                /* default location and basic options... */
                const latlng=new google.maps.LatLng( 51.512547, -0.134022 );
                const options = {
                    zoom: 18,
                    center:latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                
                /* Pinned location - stored in localStorage */
                const STORE='gmap-location';
                /*
                    if the store does not exist, 
                    create it with basic options.
                */
                if( localStorage.getItem( STORE )==null ){
                    localStorage.setItem( STORE, JSON.stringify( { lat:latlng.lat(), lng:latlng.lng(), zoom:options.zoom, type:options.mapTypeId } ) );
                }
                /* fetch details from local storage container */
                let json=JSON.parse( localStorage.getItem( STORE ) );
                /* update map configuration options with saved values */
                options.center=new google.maps.LatLng( json.lat,json.lng );
                options.zoom=json.zoom;
                options.mapTypeId=json.type;
                
                
                
                /* create the map... */
                const map = new google.maps.Map( document.getElementById('map'), options );
                
                
                
                
                const addMarker=function( latlng ){
                    /*
                        add a basic marker ( using only latlng )
                        - additional settings can be assigned 
                        as second argument - Object.
                    */
                    let a=arguments;
                    let args={
                        position:latlng,
                        map:map
                    };
                    if( typeof( a[1] )=='object' && Object.keys( a[1] ).length > 0 ){
                        args=Object.assign( args, a[1] );
                    }

                    let marker=new google.maps.Marker( args );
                    return marker;
                };
                
                
                
                
                const mapclickhandler=function(e){
                    /*
                        The user clicks on the map
                        and that location is used 
                        as the "pinned" location -
                        location & zoom are stored
                        in local storage.
                    */
                    addMarker( e.latLng );
                    map.setCenter( e.latLng );
                    localStorage.setItem( STORE, JSON.stringify( { lat:e.latLng.lat(), lng:e.latLng.lng(), zoom:map.getZoom(), type:map.getMapTypeId() } ) );
                    location.reload();
                };
                
                
                
                
                const bttnclickhandler=function( event ){
                    if( this.name=='reset' ){
                        localStorage.removeItem( STORE );
                        location.reload();
                    }else{
                        /*
                            Pin-It
                            ------
                            The user's location is found using `navigator.geolocation`
                            a marker is added at that location and the location & zoom
                            are stored in local storage
                        */
                        const evtSuccess=function(pos){
                            const latlng=new google.maps.LatLng( pos.coords.latitude, pos.coords.longitude );
                            addMarker( latlng );
                            map.setCenter( latlng );
                            localStorage.setItem( STORE, JSON.stringify( { lat:pos.coords.latitude, lng:pos.coords.longitude, zoom:map.getZoom() } ) );
                        };
                        
                        const evtFailure=function( err ){
                            console.warn( err )
                        };
                        const args={ enableHighAccuracy:true, timeout:10000 };
                        navigator.geolocation.getCurrentPosition( evtSuccess, evtFailure, args );               
                    }
                }
                
                
                
                
                /* respond to button clicks */
                let bttns=document.querySelectorAll('[type="button"]');
                    bttns.forEach( bttn=>bttn.addEventListener( 'click', bttnclickhandler ) );
                
                
                /* respond to map clicks */
                google.maps.event.addListener( map, 'click', mapclickhandler );
                
                
                /* add marker for default location */
                addMarker( map.getCenter() );
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=<APIKEY>&callback=initMap'></script>
    </head>
    <body>
        <div id='map'></div>
        <input type='button' name='pin' value='Pin It' />
        <input type='button' name='reset' value='Reset' />
    </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...