Java源码示例:com.esri.core.map.CallbackListener
示例1
private void executeDriveTimes(Graphic startPointGraphic) {
// create a Geoprocessor that points to the remote geoprocessing service.
Geoprocessor geoprocessor = new Geoprocessor(URL_GEOPROCESSING_SERVICE);
// set the output and process spatial reference to the map's spatial reference
geoprocessor.setOutSR(jMap.getSpatialReference());
geoprocessor.setProcessSR(jMap.getSpatialReference());
// initialize the required input parameters: refer to help link in the
// geoprocessing service URL for a list of required parameters
List<GPParameter> gpInputParams = new ArrayList<GPParameter>();
GPFeatureRecordSetLayer gpInputStartpoint = new GPFeatureRecordSetLayer("Input_Location");
gpInputStartpoint.addGraphic(startPointGraphic);
GPString gpInputDriveTimes = new GPString("Drive_Times");
gpInputDriveTimes.setValue("1 2 3");
gpInputParams.add(gpInputStartpoint);
gpInputParams.add(gpInputDriveTimes);
geoprocessor.executeAsync(gpInputParams, new CallbackListener<GPParameter[]>() {
@Override
public void onError(Throwable th) {
th.printStackTrace();
}
@Override
public void onCallback(GPParameter[] result) {
processResult(result);
}
});
}
示例2
protected void solveRoute() {
// ROUTING
RoutingTask task = new RoutingTask(
"http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
credentials);
RoutingTaskParameters parameters = new RoutingTaskParameters();
stops.setSpatialReference(map.getSpatialReference());
parameters.setStops(stops);
parameters.setOutSpatialReference(map.getSpatialReference());
task.solveAsync(parameters, new CallbackListener<RoutingResult>() {
@Override
public void onError(Throwable e) {
e.printStackTrace();
JOptionPane.showMessageDialog(map.getParent(),
"An error has occured. "+e.getLocalizedMessage(), "", JOptionPane.WARNING_MESSAGE);
}
@Override
public void onCallback(RoutingResult result) {
if (result != null ) {
Route topRoute = result.getRoutes().get(0);
Graphic routeGraphic = new Graphic(topRoute.getRoute().getGeometry(),
new SimpleLineSymbol(Color.BLUE, 2.0f));
stopGraphics.addGraphic(routeGraphic);
}
}
});
}
示例3
@Override
public void onMouseClicked(MouseEvent event) {
graphicsLayer.removeAll();
// add buffer as a graphic
Point mapPoint = map.toMapPoint(event.getX(), event.getY());
final Geometry buffer = GeometryEngine.buffer(
mapPoint, map.getSpatialReference(), 200000, map.getSpatialReference().getUnit());
graphicsLayer.addGraphic(new Graphic(buffer, new SimpleFillSymbol(new Color(255, 0, 0, 255))));
// get states at the buffered area
QueryTask queryTask = new QueryTask(featureLayer.getUrl());
QueryParameters queryParams = new QueryParameters();
queryParams.setInSpatialReference(map.getSpatialReference());
queryParams.setOutSpatialReference(map.getSpatialReference());
queryParams.setGeometry(buffer);
queryParams.setReturnGeometry(true);
queryParams.setOutFields(new String[] {"STATE_NAME"});
queryTask.execute(queryParams, new CallbackListener<FeatureResult>() {
@Override
public void onError(Throwable arg0) {
// deal with any exception
}
@Override
public void onCallback(FeatureResult result) {
for (Object objFeature : result) {
Feature feature = (Feature) objFeature;
graphicsLayer.addGraphic(new Graphic(feature.getGeometry(), stateSymbol));
graphicsLayer.addGraphic(new Graphic(buffer, new SimpleFillSymbol(new Color(255, 0, 0, 255))));
}
}
});
}
示例4
@Override
public void onMouseClicked(MouseEvent event) {
graphicsLayer.removeAll();
// add buffer as a graphic
Point mapPoint = map.toMapPoint(event.getX(), event.getY());
Geometry buffer = GeometryEngine.buffer(
mapPoint, map.getSpatialReference(), 200000, map.getSpatialReference().getUnit());
graphicsLayer.addGraphic(new Graphic(buffer, new SimpleFillSymbol(new Color(100, 0, 0, 80))));
// get states at the buffered area
QueryTask queryTask = new QueryTask(featureLayer.getUrl());
QueryParameters queryParams = new QueryParameters();
queryParams.setInSpatialReference(map.getSpatialReference());
queryParams.setOutSpatialReference(map.getSpatialReference());
queryParams.setGeometry(buffer);
queryParams.setReturnGeometry(true);
queryParams.setOutFields(new String[] {"STATE_NAME"});
queryTask.executeAsync(queryParams, new CallbackListener<FeatureResult>() {
@Override
public void onError(Throwable arg0) {
// deal with any exception
}
@Override
public void onCallback(FeatureResult result) {
for (Object objFeature : result) {
Feature feature = (Feature) objFeature;
graphicsLayer.addGraphic(new Graphic(feature.getGeometry(), stateSymbol));
}
}
});
}
示例5
/**
* Shows the panel with the current result.
*/
public void showCurrentResult() {
if (-1 != identifyFeatureGraphicUid) {
graphicsLayer.removeGraphic(identifyFeatureGraphicUid);
}
jPanel_results.removeAll();
Geometry geom = null;
if (null == results || 0 >= results.length) {
jLabel_counter.setText("0 of 0");
jLabel_resultName.setText("");
jLabel_distance.setText("Distance:");
jLabel_bearing.setText("Bearing:");
} else {
if (results.length <= currentIndex) {
currentIndex = 0;
} else if (0 > currentIndex) {
currentIndex = results.length - 1;
}
jLabel_counter.setText((currentIndex + 1) + " of " + results.length);
final IdentifiedItem result = results[currentIndex];
geom = result.getGeometry();
//Get attachments, if they are available
Layer resultLayer = (null == resultToLayer ? null : resultToLayer.get(result));
final ArcGISFeatureLayer featureLayer = mapController.getFeatureLayer(resultLayer, result.getLayerId());
if (null != featureLayer && featureLayer.hasAttachments()) {
featureLayer.queryAttachmentInfos(Integer.parseInt((String) result.getAttributes().get(featureLayer.getObjectIdField())), new CallbackListener<AttachmentInfo[]>() {
public void onCallback(AttachmentInfo[] attachmentInfos) {
finishShowingResult(result, attachmentInfos, featureLayer);
}
public void onError(Throwable e) {
finishShowingResult(result);
}
});
} else {
finishShowingResult(result);
}
}
//Show distance and bearing from GPS location if available
synchronized (gpsLocationLatLonLock) {
boolean showedDistanceAndBearing = false;
if (null != gpsLocationLatLon) {
//Show them
Point destinationMap = (geom instanceof Point) ? ((Point) geom) : identifyPoint;
Point gpsLocationMap = (Point) GeometryEngine.project(gpsLocationLatLon, Utilities.WGS84, mapController.getSpatialReference());
double distance = Math.sqrt(Math.pow(destinationMap.getX() - gpsLocationMap.getX(), 2.0) + Math.pow(destinationMap.getY() - gpsLocationMap.getY(), 2.0));
Point destinationLatLon = (Point) GeometryEngine.project(destinationMap, mapController.getSpatialReference(), Utilities.WGS84);
double bearing = Utilities.calculateBearingDegrees(gpsLocationLatLon, destinationLatLon);
jLabel_distance.setText("Distance: " + Math.round(distance) + " " + mapController.getSpatialReference().getUnit().getAbbreviation());
jLabel_bearing.setText("Bearing: " + Math.round(bearing) + "\u00B0");
showedDistanceAndBearing = true;
}
if (!showedDistanceAndBearing) {
jLabel_distance.setText("");
jLabel_bearing.setText("");
}
}
}
示例6
/**
* Calculates the viewshed based on the given parameters.
* @param centerPoint the center of the viewshed.
* @param radius the viewshed radius, in map units.
*/
public void calculateViewshed(Point centerPoint, double radius) {
try {
fireGPStarted();
ArrayList<GPParameter> parameters = new ArrayList<GPParameter>();
Graphic centerGraphic = new Graphic(centerPoint, VIEWSHED_CENTER_SYMBOL);
GPFeatureRecordSetLayer pointParam = new GPFeatureRecordSetLayer(observerParamName);
pointParam.setGeometryType(Geometry.Type.POINT);
pointParam.setSpatialReference(mapController.getSpatialReference());
pointParam.addGraphic(centerGraphic);
GPLinearUnit radiusParam = new GPLinearUnit(radiusParamName);
radiusParam.setUnits("esri" + mapController.getSpatialReference().getUnit().toString());
radiusParam.setDistance(radius);
GPDouble heightParam = new GPDouble(observerHeightParamName);
heightParam.setValue(observerHeight);
GPString rasterParam = new GPString(elevationParamName);
rasterParam.setValue(elevationPath);
parameters.add(pointParam);
parameters.add(radiusParam);
parameters.add(heightParam);
// parameters.add(rasterParam);//TODO add this back in if/when we want to pass a raster as a parameter
getGeoprocessor().submitJobAsync(parameters, new CallbackListener<GPJobResource>() {
public void onCallback(GPJobResource gpJobResource) {
//Display the raster as an overlay
JobStatus jobStatus = gpJobResource.getJobStatus();
ArcGISDynamicMapServiceLayer layer = null;
switch (jobStatus) {
case SUCCEEDED: {
layer = new ArcGISDynamicMapServiceLayer(getGeoprocessor().getUrl(), gpJobResource);
//Don't break
}
case CANCELLED:
case DELETED:
case FAILED:
case TIMED_OUT: {
fireGPEnded(layer);
break;
}
default: {
try {
Thread.sleep(1000 / 24);
} catch (InterruptedException ex) {
Logger.getLogger(ViewshedController.class.getName()).log(Level.SEVERE, null, ex);
}
getGeoprocessor().getJobStatusAsync(this);
}
}
}
public void onError(Throwable e) {
fireGPEnded(null);
Logger.getLogger(ViewshedController.class.getName()).log(Level.SEVERE, null, e);
}
});
} catch (Throwable t) {
fireGPEnded(null);
Logger.getLogger(ViewshedController.class.getName()).log(Level.SEVERE, null, t);
}
}
示例7
/**
* Handles issuing a response to a FeatureType response. A FeatureType response
* indicates that the Wear devices wants a feature of the specified FeatureType
* to be collected at the current device location.
*
* @param event the MessageEvent from the Wear device
* @param client the Google API client used to communicate
*/
private void handleFeatureTypeResponse(final MessageEvent event, final GoogleApiClient client) {
// Create a PutDataMapRequest with the status response path
final PutDataMapRequest req = PutDataMapRequest.create(STATUS_RESPONSE);
final DataMap dm = req.getDataMap();
// Put the current time into the data map, which forces an onDataChanged event (this event
// only occurs when data actually changes, so putting the time ensures something always changes)
dm.putLong("Time", System.currentTimeMillis());
try {
// Request a single high precision location update
LocationRequest request = LocationRequest.create()
.setNumUpdates(1)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(client, request, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// When we've got a location, get the FeatureType that matches the specified name
Log.i("Test", "Received location");
String featureTypeName = new String(event.getData());
FeatureType type = null;
for (FeatureType ft : sArcGISFeatureLayer.getTypes()) {
if (ft.getName().equals(featureTypeName)) {
type = ft;
break;
}
}
// Only proceed if we found a matching type (which we always should)
if (type != null) {
// Create a new feature of the specified type at the current location
Graphic g = sArcGISFeatureLayer.createFeatureWithType(type, new Point(location.getLongitude(), location.getLatitude()));
// Apply the edit to the service
sArcGISFeatureLayer.applyEdits(new Graphic[]{g}, null, null, new CallbackListener<FeatureEditResult[][]>() {
@Override
public void onCallback(FeatureEditResult[][] featureEditResults) {
// Check that we have a success and report success
if (featureEditResults[0].length > 0) {
FeatureEditResult fer = featureEditResults[0][0];
if (fer.isSuccess()) {
Log.i("Test", "Successfully added feature");
// Put a boolean indicating success into the data map
dm.putBoolean("success", true);
} else {
Log.e("Test", "Failed to add feature: " + fer.getError().getDescription());
// Put a boolean indicating failure into the data map
dm.putBoolean("success", false);
// Put a string with the reason for failure into the data map
dm.putString("reason", "Error code: " + fer.getError().getCode());
}
}
// Put the DataItem into the Data API stream
Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
}
@Override
public void onError(Throwable throwable) {
Log.d("Test", "Failed to add new graphic");
// Put a boolean indicating failure into the data map
dm.putBoolean("success", false);
// Put a string with the reason for failure into the data map
dm.putString("reason", throwable.getLocalizedMessage());
// Put the DataItem into the Data API stream
Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
}
});
} else {
// If we don't have a matching feature type (which should never happen), log an error
Log.e("Test", "Could not determine type");
// Put a boolean indicating failure into the data map
dm.putBoolean("success", false);
// Put a string with the reason for failure into the data map
dm.putString("reason", "Specified type not found");
// Put the DataItem into the Data API stream
Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
}
}
});
} catch (SecurityException se) {
// If we caught an exception trying to get the location, likelihood is that the location
// permission has not been granted by the user
Log.e("Test", "Could not access location");
// Put a boolean indicating failure into the data map
dm.putBoolean("success", false);
// Put a string with the reason for failure into the data map
dm.putString("reason", "Could not access location. Check permissions.");
// Put the DataItem into the Data API stream
Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
}
}
示例8
/**
* Collects a feature of the specified type at the current device location.
*
* @param featureTypeName the type of feature to collect
*/
private void collectFeature(final String featureTypeName) {
try {
// Request a single high precision location update
LocationRequest request = LocationRequest.create()
.setNumUpdates(1)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// When we've got a location, get the FeatureType that matches the specified name
FeatureType type = null;
for (FeatureType ft : mArcGISFeatureLayer.getTypes()) {
if (ft.getName().equals(featureTypeName)) {
type = ft;
break;
}
}
// Only proceed if we found a matching type (which we always should)
if (type != null) {
// Create a new feature of the specified type at the current location
Graphic g = mArcGISFeatureLayer.createFeatureWithType(type, new Point(location.getLongitude(), location.getLatitude()));
// Apply the edit to the service
mArcGISFeatureLayer.applyEdits(new Graphic[]{g}, null, null, new CallbackListener<FeatureEditResult[][]>() {
@Override
public void onCallback(FeatureEditResult[][] featureEditResults) {
// Check that we have a success and report success
if (featureEditResults[0].length > 0) {
FeatureEditResult fer = featureEditResults[0][0];
if (fer.isSuccess()) {
Log.i("Test", "Successfully added feature: " + fer.getObjectId());
Toast.makeText(CollectionActivity.this, "Successful collection!", Toast.LENGTH_SHORT).show();
} else {
Log.e("Test", "Failed to add feature: " + fer.getError().getDescription());
}
}
}
@Override
public void onError(Throwable throwable) {
Log.e("Test", "Failed to add new graphic");
}
});
} else {
// If we don't have a matching feature type (which should never happen), log an error
Log.e("Test", "Could not determine type");
}
}
});
} catch (SecurityException se) {
// If we caught an exception trying to get the location, likelihood is that the location
// permission has not been granted by the user
Log.e("Test", "Could not access location. Check permissions.");
}
}
示例9
protected void onFind() {
Locator locator = new Locator(
"http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
LocatorFindParameters params = new LocatorFindParameters(textField.getText());
params.setOutSR(map.getSpatialReference());
// additional parameters optionally, could grab the latest point from a GPS feed for example
params.setLocation(new Point(-356903.5435, 7546014.500), map.getSpatialReference());
params.setDistance(10000);
// run the locator task asynchronously
locator.findAsync(params, new CallbackListener<List<LocatorGeocodeResult>>() {
@Override
public void onError(Throwable e) {
JOptionPane.showMessageDialog(map.getParent(), e.getMessage());
}
@Override
public void onCallback(List<LocatorGeocodeResult> results) {
// display top result
if (results != null) {
// get the top result to display on map
LocatorGeocodeResult highestScoreResult = results.get(0);
// create and populate attribute map
Map<String, Object> attributes = new HashMap<String, Object>();
for (Entry<String, String> entry : highestScoreResult.getAttributes().entrySet())
{
attributes.put(entry.getKey(), entry.getValue());
}
// create a graphic at this location
Graphic addressGraphic = new Graphic(
highestScoreResult.getLocation(),
geocodeSymbol,
attributes,
null);
addressGraphics.addGraphic(addressGraphic);
// centre the map at this location
Envelope extent = map.getExtent();
extent.centerAt(highestScoreResult.getLocation());
map.zoomTo(extent);
}
}
});
}
示例10
private void executeDriveTimes(Graphic startPointGraphic) {
// create a Geoprocessor that points to the remote geoprocessing service.
Geoprocessor geoprocessor = new Geoprocessor(URL_GEOPROCESSING_SERVICE);
// set the output and process spatial reference to the map's spatial reference
SpatialReference outSR = SpatialReference.create(4326);
Geometry projectedStartPoint = GeometryEngine.project(
startPointGraphic.getGeometry(), jMap.getSpatialReference(), outSR);
Graphic projectedStartPointGraphic = new Graphic(projectedStartPoint, startPointGraphic.getSymbol());
geoprocessor.setOutSR(outSR);
geoprocessor.setProcessSR(outSR);
// initialize the required input parameters: refer to help link in the
// geoprocessing service URL for a list of required parameters
List<GPParameter> gpInputParams = new ArrayList<GPParameter>();
GPFeatureRecordSetLayer gpInputStartpoint = new GPFeatureRecordSetLayer("Input_Location");
gpInputStartpoint.addGraphic(projectedStartPointGraphic);
//GPString gpInputDriveTimes = new GPString("Drive_Time");
// Tip: use GP service info to get the parameter names
GPString gpInputDriveTimes = new GPString("Drive_Times");
gpInputDriveTimes.setValue("1 2 3");
gpInputParams.add(gpInputStartpoint);
gpInputParams.add(gpInputDriveTimes);
// execute the geoprocessing request
/*try {
GPParameter[] result = geoprocessor.execute(gpInputParams);
updateProgresBarUI(null, tasksInProgress.decrementAndGet() > 0);
processResult(result);
} catch (Exception ex) {
JOptionPane.showMessageDialog(map, ex.getMessage(), "", JOptionPane.ERROR_MESSAGE);
}*/
// Tip: Do not block UI thread.
geoprocessor.executeAsync(
gpInputParams,
new CallbackListener<GPParameter[]>() {
@Override
public void onError(Throwable th) {
th.printStackTrace();
}
@Override
public void onCallback(GPParameter[] result) {
updateProgresBarUI(null, tasksInProgress.decrementAndGet() > 0);
processResult(result);
}
}
);
}
示例11
/**
* Handle mouse-clicks.
* On left-click - draws either a polyline or a point.
* On right-click - computes and draws the buffer of the polyline or point.
*/
@Override
public void onMouseMoved(MouseEvent event) {
super.onMouseMoved(event);
gLayer.removeAll();
Point currPoint = jMap.toMapPoint(event.getX(), event.getY());
// point
bufferedArea = GeometryEngine.buffer(
currPoint,
jMap.getSpatialReference(),
BUFFER_DISTANCE,
jMap.getSpatialReference().getUnit());
Graphic currPointGraphic = new Graphic(currPoint, GeometryOfflineApp.SYM_POINT);
gLayer.addGraphic(currPointGraphic);
// add the buffered area to the graphics layer
Graphic bufferedGraphic = new Graphic(bufferedArea, GeometryOfflineApp.SYM_BUFFER);
gLayer.addGraphic(bufferedGraphic);
if (queryInProgress.get() == false) {
// query
QueryParameters query = new QueryParameters();
query.setReturnGeometry(true);
query.setGeometry(bufferedArea);
query.setOutFields(new String[] {"STATE_NAME"});
// execute the query.
table.queryFeatures(query, new CallbackListener<FeatureResult>() {
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onCallback(FeatureResult result) {
gLayerResults.removeAll();
for (Object objFeature : result) {
Feature feature = (Feature) objFeature;
gLayerResults.addGraphic(new Graphic(feature.getGeometry(), SYM_BUFFER));
}
queryInProgress.set(false);
}
});
queryInProgress.set(true);
}
prevPoint = null;
polyLine.setEmpty();
return;
}
示例12
/**
* Handle mouse-clicks.
* On left-click - draws either a polyline or a point.
* On right-click - computes and draws the buffer of the polyline or point.
*/
@Override
public void onMouseMoved(MouseEvent event) {
super.onMouseMoved(event);
gLayer.removeAll();
Point currPoint = jMap.toMapPoint(event.getX(), event.getY());
// point
bufferedArea = GeometryEngine.buffer(
currPoint,
jMap.getSpatialReference(),
BUFFER_DISTANCE,
jMap.getSpatialReference().getUnit());
Graphic currPointGraphic = new Graphic(currPoint, GeometryApp.SYM_POINT);
gLayer.addGraphic(currPointGraphic);
// add the buffered area to the graphics layer
Graphic bufferedGraphic = new Graphic(bufferedArea, GeometryApp.SYM_BUFFER);
gLayer.addGraphic(bufferedGraphic);
if (queryInProgress.get() == false) {
// query
QueryParameters query = new QueryParameters();
query.setReturnGeometry(true);
query.setGeometry(bufferedArea);
query.setOutFields(new String[] {"STATE_NAME"});
// execute the query.
table.queryFeatures(query, new CallbackListener<FeatureResult>() {
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onCallback(FeatureResult result) {
gLayerResults.removeAll();
for (Object objFeature : result) {
Feature feature = (Feature) objFeature;
gLayerResults.addGraphic(new Graphic(feature.getGeometry(), SYM_BUFFER));
}
queryInProgress.set(false);
}
});
queryInProgress.set(true);
}
prevPoint = null;
polyLine.setEmpty();
return;
}