我的Web应用程序中有一个世界地图,由Amcharts4提供支持。我想在地图上添加一个标记,显示用户的地理位置(使用HTML5 getCurrentPosition函数。但是地图在检索坐标时已经生成,绘制新标记后如何将新标记推送到地图上?
我有Amcharts地图的工作版本,包括地图上的标记,以及地理定位功能。地理位置异步工作,脚本在检索位置时继续,因此在此期间生成地图。我不太喜欢在继续之前等待找到坐标,因为这可能意味着几秒钟的延迟。
本质上,我正在寻找在显示该对象后将标记数据推送到我的 Amcharts 对象的功能。这是我的地图js:
// Themes begin
am4core.useTheme(am4themes_animated);
// Create map instance
var chart = am4core.create("chartdiv", am4maps.MapChart);
// Set map definition
chart.geodata = am4geodata_worldLow;
// Set projection
chart.projection = new am4maps.projections.Miller();
// Series for World map
var worldSeries = chart.series.push(new am4maps.MapPolygonSeries());
worldSeries.exclude = ["AQ"];
worldSeries.useGeodata = true;
worldSeries.data = mapdata;
var polygonTemplate = worldSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{text}";
polygonTemplate.adapter.add("tooltipText", function(text, ev) {
if (!ev.dataItem.dataContext.text) {
return "{name}";
}
return text;
})
polygonTemplate.fill = chart.colors.getIndex(0);
polygonTemplate.nonScalingStroke = true;
polygonTemplate.propertyFields.fill = "fill";
polygonTemplate.properties.fill = am4core.color("#dddddd");
chart.zoomControl = new am4maps.ZoomControl();
// Hover state
var hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#333");
// Create image series
var imageSeries = chart.series.push(new am4maps.MapImageSeries());
// Create a circle image in image series template so it gets replicated to all new images
var imageSeriesTemplate = imageSeries.mapImages.template;
var circle = imageSeriesTemplate.createChild(am4core.Circle);
circle.radius = 4;
circle.fill = am4core.color("#000");
circle.stroke = am4core.color("#FFFFFF");
circle.strokeWidth = 2;
circle.nonScaling = true;
circle.tooltipText = "{title}";
// Set property fields
imageSeriesTemplate.propertyFields.latitude = "latitude";
imageSeriesTemplate.propertyFields.longitude = "longitude";
// Add data for the three cities
imageSeries.data = [{
"latitude": 51.561678,
"longitude": 5.049685,
"title": "Rural Spark HQ"
}];
if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); }
function showPosition(position) {
clientlocation = ({"latitude": position.coords.latitude, "longitude": position.coords.longitude, "title": "I am here!"});
console.log(clientlocation)
//push this clientlocation data to the map somehow?
}
我可以在控制台中看到客户端位置,但我没有找到任何方法在地图上获取它。
您可以将新对象 ( clientlocation
( 添加到imageSeries.data
:
imageSeries.addData(clientlocation);
或者,您可以通过重新分配数据字段来添加数据:
imageSeries.data = [...imageSeries.data, clientlocation];
这是一个代码笔作为参考。