如何显示标记周围的圆圈?

时间:2018-07-25 09:28:38

标签: javascript leaflet

我正在尝试在标记周围显示一个圆圈,以告诉用户该标记的范围。到目前为止,我已经尝试了以下代码。我无法显示圈子。 我想要这样的东西。 enter image description here

var map = L.map('map').setView([42.35, -71.08], 13);
var userLocation = new L.LatLng(42.237, -71.96);
L.tileLayer('http://tiles.mapc.org/basemap/{z}/{x}/{y}.png', {
  attribution: 'Tiles by <a href="http://mapc.org">MAPC</a>, Data by <a href="http://mass.gov/mgis">MassGIS</a>',
  maxZoom: 17,
  minZoom: 9
}).addTo(map);

var marker = L.marker(userLocation).addTo(map);

var circle = L.circle(userLocation, {
  color: 'red',
  fillColor: '#f03',
  fillOpacity: 0.5,
  radius: 500
}).addTo(map);
.container {
  width: 800px;
  margin: 20px auto;
}

#map {
  width: 800px;
  height: 450px;
  border: 1px solid #AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/0.4.0/MarkerCluster.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/0.4.0/leaflet.markercluster.js'></script>

<div class="container">
  <h1>Maps:</h1>
  <div id="map"></div>
</div>

1 个答案:

答案 0 :(得分:2)

已绘制了圆,但是放置圆的坐标已超出视口。

缩小3步,看到它位于Spencer和Leicester之间(沿着西南方向从波士顿乘坐I-90)。

首先在代码中设置用户位置,并将其用于视口定义,标记和圆的放置。

>

独立代码:

var userLocation = new L.LatLng(42.35, -71.08);
var map = L.map('map').setView(userLocation, 13);
//...
var marker = L.marker(userLocation).addTo(map);
//...
var circle = L.circle(userLocation, {
//...

演示

查看此JSFiddle

更新

Q引用了过时的传单版本和CDN,它们在当前发行版中似乎存在一些问题。

使用以下资源网址,一切正常:

var userLocation = new L.LatLng(42.35, -71.08);
var map = L.map('map').setView(userLocation, 13);
L.tileLayer('http://tiles.mapc.org/basemap/{z}/{x}/{y}.png',
{
    attribution: 'Tiles by <a href="http://mapc.org">MAPC</a>, Data by <a href="http://mass.gov/mgis">MassGIS</a>',
    maxZoom: 17,
    minZoom: 9
}).addTo(map);

var marker = L.marker(userLocation).addTo(map);

var circle = L.circle(userLocation, {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5,
    radius: 500
}).addTo(map);