首页 > 解决方案 > Map Center 和 Marker 基于文本输入创建

问题描述

我想根据文本输入 HTML 定义地图中心和标记

当我在输入文本上输入 lat/long 时它可以工作,但我需要按 Enter 才能使其工作,我希望它会在地图加载而不按 Enter 的情况下工作,

<a id="myloc" type="text">-7.3344454, 112.7898796</a>
<button onclick="w3Load()">Load The Map</button>
<div id="map"></div>

Java 脚本:

  function initAutocomplete() {
    var input11 = document.getElementById("myloc").value
    var input23  = new google.maps.LatLng(input11);
    //var input23 = new google.maps.LatLng(document.getElementById("pac-input").value;  
    var map = new google.maps.Map(document.getElementById('map'), {
      //center: {lat: -33.8688, lng: 151.2195},
      center: input23,
      zoom: 13,
      mapTypeId: 'roadmap'
    });

    // Create the search box and link it to the UI element.
    var input = document.getElementById('myloc');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function() {
      searchBox.setBounds(map.getBounds());
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
      var places = searchBox.getPlaces();

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

      // Clear out the old markers.
      markers.forEach(function(marker) {
        marker.setMap(null);
      });
      markers = [];

      // 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;
        }
        var 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(25, 25)
        };

        // Create a marker for each place.
        markers.push(new google.maps.Marker({
          map: map,
          icon: icon,
          title: place.name,
          position: place.geometry.location
        }));

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      map.fitBounds(bounds);
    });
  }

function mapLoad(){
        document.getElementById("map").style.display = 'block';
        google.maps.event.trigger(map, 'resize');
}

我预计它会在地图加载而不按 Enter 的情况下工作,因为 lat long 是根据另一个输入表单自动生成的

标签: google-mapsgoogle-maps-markers

解决方案


我收到您问题中的代码的 javascript 错误:InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value.因为input11为空。

我相信你想做的是:

  1. 使用 id="myloc" 使您的元素成为 HTML<input>元素(文本),并将其值设置为以逗号分隔的纬度、经度坐标字符串。
<input id="myloc" type="text" value="-7.3344454, 112.7898796" />
  1. 解析该.value元素以分离出两个数字(google.maps.LatLng对象将两个数字作为参数,而不是逗号分隔的字符串):
var input11 = document.getElementById("myloc").value
var coords = input11.split(",");
var input23  = new google.maps.LatLng(coords[0], coords[1]);
  1. 使用结果google.maps.LatLng来初始化地图的中心和标记的位置:
var map = new google.maps.Map(document.getElementById('map'), {
  center: input23,
  zoom: 13,
  mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
  map: map,
  position: map.getCenter()
})

把它们放在一起:

function initAutocomplete() {
  var input11 = document.getElementById("myloc").value
  var coords = input11.split(",");
  var input23  = new google.maps.LatLng(coords[0], coords[1]);
  var map = new google.maps.Map(document.getElementById('map'), {
    center: input23,
    zoom: 13,
    mapTypeId: 'roadmap'
  });
  var marker = new google.maps.Marker({
    map: map,
    position: map.getCenter()
  });

概念证明小提琴

结果地图的屏幕截图

代码片段:

function initAutocomplete() {
  var input11 = document.getElementById("myloc").value
  var coords = input11.split(",");
  var input23 = new google.maps.LatLng(coords[0], coords[1]);
  var map = new google.maps.Map(document.getElementById('map'), {
    center: input23,
    zoom: 13,
    mapTypeId: 'roadmap'
  });
  var marker = new google.maps.Marker({
    map: map,
    position: map.getCenter()
  })
  // Create the search box and link it to the UI element.
  var input = document.getElementById('myloc');
  var searchBox = new google.maps.places.SearchBox(input);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });

  var markers = [];
  // Listen for the event fired when the user selects a prediction and retrieve
  // more details for that place.
  searchBox.addListener('places_changed', function() {
    var places = searchBox.getPlaces();

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

    // Clear out the old markers.
    markers.forEach(function(marker) {
      marker.setMap(null);
    });
    markers = [];

    // 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;
      }
      var 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(25, 25)
      };

      // Create a marker for each place.
      markers.push(new google.maps.Marker({
        map: map,
        icon: icon,
        title: place.name,
        position: place.geometry.location
      }));

      if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
      } else {
        bounds.extend(place.geometry.location);
      }
    });
    map.fitBounds(bounds);
  });
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<input id="myloc" type="text" value="-7.3344454, 112.7898796" />
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete" async defer></script>


推荐阅读