Capture pointer movement in Google Maps

0

Good, I have this code that I must implement in a form ... What I need to do with it is that the user can mark the location of his home to later save it in the database ... My problem is that no I can capture when the pointer / click on the map moves, therefore, I can not capture the coordinates ...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Pragma" content="no-cache" />

    <style type="text/css">
        label{
            width: 70px;float:left;
            padding-top: 3px;
        }
    </style>
    <script src="assets/js/jquery-1.11.js"></script>

    <script type="text/javascript">
        //Declaramos las variables que vamos a user
        var lat = null;
        var lng = null;
        var map = null;
        var geocoder = null;
        var marker = null;

        jQuery(document).ready(function() {
            //obtenemos los valores en caso de tenerlos en un formulario ya guardado en la base de datos
            lat = jQuery('#lat').val();
            lng = jQuery('#long').val();
            //Asignamos al evento click del boton la funcion codeAddress
            jQuery('#pasar').click(function() {
                codeAddress();
                return false;
            });
            //Inicializamos la función de google maps una vez el DOM este cargado
            initialize();
        });

        function initialize() {

            geocoder = new google.maps.Geocoder();

            //Si hay valores creamos un objeto Latlng
            if (lat != '' && lng != '') {
                var latLng = new google.maps.LatLng(lat, lng);
            } else {
                var latLng = new google.maps.LatLng(-25.3099006,-57.5942891);
            }
            //Definimos algunas opciones del mapa a crear
            var myOptions = {
                center: latLng, //centro del mapa
                zoom: 13, //zoom del mapa
                mapTypeId: google.maps.MapTypeId.ROADMAP //tipo de mapa, carretera, híbrido,etc
            };
            //creamos el mapa con las opciones anteriores y le pasamos el elemento div
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            //creamos el marcador en el mapa
            marker = new google.maps.Marker({
                map: map, //el mapa creado en el paso anterior
                position: latLng, //objeto con latitud y longitud
                draggable: true //que el marcador se pueda arrastrar
            });

            //función que actualiza los input del formulario con las nuevas latitudes
            //Estos campos suelen ser hidden
            updatePosition(latLng);


        }


        //funcion que simplemente actualiza los campos del formulario
        function updatePosition(latLng) {

            jQuery('#lat').val(latLng.lat());
            jQuery('#long').val(latLng.lng());

        }
    </script>

</head>
<body>
    <form id="google" name="google" action="#">        

        <div id="map_canvas" style="width:800px;height:300px;"></div>

        <br/>
        <p><label>Latitud: </label><input type="text" readonly name="lat" id="lat"/></p>
        <p><label> Longitud:</label> <input type="text" readonly name="lng" id="long"/></p>

    </form>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?key={borrado_por_seguridad}"></script> 
</body>
</html>

Could someone enlighten me by telling me what I'm missing so that it works correctly?

Thanks and Regards:)

    
asked by KuroNeko 01.02.2018 в 21:15
source

2 answers

2

You can add a listener to your map and capture when the user changes the position of the marker, like this:

function initMap(lat, lng, zoom) {
  // lat = 20.973276, lng = -89.624175, zoom = 12
  lat = typeof lat === 'undefined' ? -0.1767189 : lat;
  lng = typeof lng === 'undefined' ? -78.4809883 : lng;
  zoom = typeof zoom === 'undefined' ? 13 : zoom;

  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: zoom,
    center: {
      lat: lat,
      lng: lng
    }
  });

  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: {
      lat: lat,
      lng: lng
    }
  });
  
  // Agregamos el listener para capturar el click y movimiento del marcador
  marker.addListener("click", function() {
    if (marker.getAnimation() !== null) {
      marker.setAnimation(null);
    } else {
      marker.setAnimation(google.maps.Animation.BOUNCE);
    }
  });
  
  // Capturamos cuando la posición del marcador cambie y realizamos la acción que se requiera
  google.maps.event.addListener(marker, "position_changed", function() {

    var lat = marker.getPosition().lat();
    var lng = marker.getPosition().lng();

    console.log('Latitude: ' + lat);
    console.log('Longitude: ' + lng);

  });
}
initMap();
<div id="map" style="width: 100%; height: 200px;"></div>
<script src='https://maps.googleapis.com/maps/api/js'></script>
    
answered by 01.02.2018 / 21:36
source
0

You can use a listener, you can click here to see the documentation. What I recommend is to capture the location by clicking on the desired place. You can do it this way (it's a basic but fully functional example for what you need):

CSS:

#map {
  height: 550px;
  width: 450px;
}

HTML:

 <!-- en los asteriscos va el API KEY -->
 <script async defer
src="https://maps.googleapis.com/maps/api/js?key=***************&callback=initMap">
<div id="map"></div>

JavaScript:

function initMap() {
    // Hacer set up del mapa
    var centro = {lat: 40.758899, lng: -73.9873197};
    map = new google.maps.Map(document.getElementById('map'), {
       center: centro,
       zoom: 15,
       streetViewControl: false
    });

    // listener que capta el click en el mapa
    google.maps.event.addListener(map, 'click', function(event) {
       var latmh = event.latLng.lat();
       var lngmh = event.latLng.lng();
       // ponemos un marcador donde se hace click
       var marker = new google.maps.Marker({
           position: event.latLng,
           map: map
       });

      console.log(latmh+" vvv "+lngmh);
    }); 
}
    
answered by 01.02.2018 в 21:41