gsvc.project(params, function (projectedPoints) {
pt = projectedPoints[0];
});
geometry.addPath(pt);
有谁可以告诉我为什么projectedPoints
只会在抛出错误后返回?代码不会进入回调并尝试在未定义数组时分配pt。这会导致代码出错,即回调最终启动时。
我一直在尝试引用here中的代码,但似乎无法弄清楚如何让回调像xample一样工作。
` var map,gsvc,pt;
require([
"esri/map", "esri/graphic", "esri/symbols/SimpleMarkerSymbol",
"esri/tasks/GeometryService", "esri/tasks/ProjectParameters",
"esri/SpatialReference", "esri/InfoTemplate", "dojo/dom", "dojo/on",
"dojo/domReady!"
], function(
Map, Graphic, SimpleMarkerSymbol,
GeometryService, ProjectParameters,
SpatialReference, InfoTemplate, dom, on
) {
map = new Map("map", {
basemap: "streets",
center: [-98.445, 46.147],
zoom: 3
});
gsvc = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
map.on("click", projectToWebMercator);
function projectToWebMercator(evt) {
map.graphics.clear();
var point = evt.mapPoint;
var symbol = new SimpleMarkerSymbol().setStyle("diamond");
var graphic = new Graphic(point, symbol);
var outSR = new SpatialReference(102100);
map.graphics.add(graphic);
gsvc.project([ point ], outSR, function(projectedPoints) {
pt = projectedPoints[0];
graphic.setInfoTemplate(new InfoTemplate("Coordinates",
"<span>X:</span>" + pt.x.toFixed() + "<br>" +
"<span>Y:</span>" + pt.y.toFixed() + "<br>" +
"<input type='button' value='Convert back to LatLong' id='convert'>" +
"<div id='latlong'></div>"));
map.infoWindow.setTitle(graphic.getTitle());
map.infoWindow.setContent(graphic.getContent());
map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
on.once(dom.byId("convert"), "click", projectToLatLong);
});
}
function projectToLatLong() {
var outSR = new SpatialReference(4326);
var params = new ProjectParameters();
params.geometries = [pt.normalize()];
params.outSR = outSR;
gsvc.project(params, function(projectedPoints) {
pt = projectedPoints[0];
dom.byId("latlong").innerHTML = "<span>Latitude: </span> " +
pt.y.toFixed(3) + "<br><span>Longitude:</span>" + pt.x.toFixed(3);
});
}
});
</script>`
答案 0 :(得分:0)
您有可变范围问题。需要在回调之外定义pt
。
var pt;
gsvc.project(params, function(projectedPoints) {
pt = projectedPoints[0];
});
geometry.addPath(pt);
修改强>
如果.project()
方法是异步的,那么Arun的回答是正确的方法。
答案 1 :(得分:0)
可能是因为项目是异步方法(如果是这样)
//looks like project is a async method
gsvc.project(params, function (projectedPoints) {
var pt = projectedPoints[0];
//do all operations which depends on pt in the callback
geometry.addPath(pt);
});
//so this part will get executed before the callback is executed so pt won't be defined