允许用户使用他们输入的半径在地图上绘制圆圈

Allow user to draw circle on the map with radius that they entered

本文关键字:地图 绘制 输入 许用户 用户 他们      更新时间:2023-09-26

我想到的是一个输入框,用户首先在其中输入半径。然后在它旁边的按钮上添加一个可拖动的圆圈到地图上。

我已经尝试了谷歌地图V3中的DrawingMode。它忽略了该半径设置。

var map;
var pos;
function initialize() {
  var mapOptions = {
    zoom: 16,
    scaleControl: false,
    zoomControl: false,
    rotateControl: false,
    streetViewControl: false,
    panControl:false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
function setCurrentLocation(){
navigator.geolocation.getCurrentPosition(function(position) {
     pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);
     map.setCenter(pos);
})}

setCurrentLocation();
function drawCircle(){
        var draw_circle = new google.maps.Circle({
        center: pos,
        radius: 200,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        map: map})}

$( "#addcircle" ).click(function() {
  drawCircle();
});

我尝试使用上述方法。但似乎变量 posdrawCircle 函数中无效。

$( "#addcircle" ).click(function() {
  drawCircle();
});

这部分与一个特定的按钮有关,一旦点击它就应该添加圆圈。

function setCurrentLocation(){
navigator.geolocation.getCurrentPosition(function(position) {
     pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);
     map.setCenter(pos);
     function drawCircle(){
        var draw_circle = new google.maps.Circle({
        center: pos,
        radius: 200,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        map: map})}
        ;
        drawCircle();
})}

如果我更改代码以测试pos,则可以使用。实际发送到圆的pos坐标有效。

但是一旦我将drawCircle();放置在按钮单击处理程序中,我就无法让该功能工作。

你确定navigator.geolocation.getCurrentPosition我的意思是为什么你不检查 setCurrentLocation() 中的 console.log(position.coords) 确保你将正确的对象"pos"发送到圆圈中

或者简单地将直接位置对象分配到地图中:new google.maps.LatLng(41.878113, -87.629798) 确保一切正常