Google Maps API 3: Get Coordinates from Right-Click

后端 未结 2 1571
攒了一身酷
攒了一身酷 2020-12-23 08:47

I have 2 text boxes for lat and lon for when a user is entering a new record to the db.

I have a live preview of Google Maps that works great, now what I want to do

相关标签:
2条回答
  • 2020-12-23 09:45
    google.maps.event.addListener(map, "rightclick", function(event) {
        var lat = event.latLng.lat();
        var lng = event.latLng.lng();
        // populate yor box/field with lat, lng
        alert("Lat=" + lat + "; Lng=" + lng);
    });
    
    0 讨论(0)
  • 2020-12-23 09:46

    You can create an InfoWindow object (class documentation here) and attach to it a rightclick event handler that will populate it with latitude and longitude of the clicked location on the map.

    function initMap() {
      var myOptions = {
          zoom: 6,
          center: new google.maps.LatLng(-33.8688, 151.2093)
        },
        map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
        marker = new google.maps.Marker({
          map: map,
        }),
        infowindow = new google.maps.InfoWindow;
      map.addListener('rightclick', function(e) {
        map.setCenter(e.latLng);
        marker.setPosition(e.latLng);
        infowindow.setContent("Latitude: " + e.latLng.lat() +
          "<br>" + "Longitude: " + e.latLng.lng());
        infowindow.open(map, marker);
      });
    }
    html,
    body {
      height: 100%;
    }
    #map-canvas {
      height: 100%;
      width: 100%;
    }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIPPUQ0PSWMjTsgvIWRRcJv3LGfRzGmnA&callback=initMap" async defer></script>
    <div id="map-canvas"></div>

    0 讨论(0)
提交回复
热议问题