如何将用户输入标记添加到网站上的Google Maps小部件,并从中获取经度和纬度数据?

问题描述 投票:0回答:1

如何在我的网站上的Google Maps小部件中添加用户输入标记,并从中获取纬度和经度数据?

现在,我正在构建一个应用程序,该应用程序必须允许用户将标记拖放到任何位置,以便我可以获取该数据并进行处理。

   <script>
                var map;
                function initMap() {
                  map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 2,
                    center: new google.maps.LatLng(2.8,-187.3),
                    mapTypeId: 'terrain'
                  });

                  // Create a <script> tag and set the USGS URL as the source.
                  var script = document.createElement('script');
                  // This example uses a local copy of the GeoJSON stored at
                  // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
                  script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
                  document.getElementsByTagName('head')[0].appendChild(script);
                }

                // Loop through the results array and place a marker for each
                // set of coordinates.
                window.eqfeed_callback = function(results) {
                  for (var i = 0; i < results.features.length; i++) {
                    var coords = results.features[i].geometry.coordinates;
                    var latLng = new google.maps.LatLng(coords[1],coords[0]);
                    var marker = new google.maps.Marker({
                      position: latLng,
                      map: map
                    });
                  }
                }
              </script>

目前,我正在使用它,但这不提供任何用户提交的标记。

html css google-maps bootstrap-4 google-maps-markers
1个回答
0
投票

尝试运行此工作jsfiddle,以进行演示并指导用户如何在Google地图上放置标记。请注意,它基于Google的example添加和删除标记。

下面的完整JS代码:

var map;
var markers = [];

function initMap() {
  var haightAshbury = {
    lat: 37.769,
    lng: -122.446
  };

  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: haightAshbury,
    mapTypeId: 'terrain'
  });

  // This event listener will call addMarker() when the map is clicked.
  map.addListener('click', function(event) {
    addMarker(event.latLng);
  });

  // Adds a marker at the center of the map.
  addMarker(haightAshbury);
}

// Adds a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markers.push(marker);
}

您可以从地图的点击事件监听器中获取标记的坐标,例如:

  map.addListener('click', function(event) {
    console.log(event.latLng.lat());
    console.log(event.latLng.lng());
    addMarker(event.latLng);
  });

或通过addMarker方法:

function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  console.log(marker.getPosition().lat());
  console.log(marker.getPosition().lng());
  markers.push(marker);
}

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.