>From the devguide examples I implemented a functionality to draw a rectangle
on the map. This partly implements the LayerDefinitionFactory in Java. It
works by drawing 4 lines which make up the rectangle.

You call the jsp froma page with this script:
    <script language="javascript" type="text/javascript">  
      function DigitizeRectangle() {
          parent.mapFrame.DigitizeRectangle(OnRectangleDigitized);
      }
      function OnRectangleDigitized(rect) {
          // Send the Javascript variables to 'draw_rect.jsp' via the form
frame
          // Vorher: var queryString =
window.top.location.search.substring(1);
          var queryString =
window.parent.parent.location.search.substring(1);
          var truffle_webapp_antrag_id = getParameter(queryString,
"truffle_webapp_antrag_id");
          var truffle_webapp_session_id = getParameter(queryString,
"truffle_webapp_session_id");
          var params = new Array("x0", rect.Point1.X,
            "y0", rect.Point1.Y,
                "x1", rect.Point2.X,
                "y1", rect.Point2.Y,
                "SESSION", this.sessionId,
                "MAPNAME", this.mapName);
         
parent.formFrame.Submit("/mapguide/javatest/digitizing_features/draw_rect.jsp",
params, "scriptFrame");
      }
    </script>  


draw_rect.jsp looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd";>
<!--
//  Copyright (C) 2004-2006  Autodesk, Inc.
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of version 2.1 of the GNU Lesser
//  General Public License as published by the Free Software Foundation.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 
USA
-->
<html>
<%@ page import="org.osgeo.mapguide.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*" %>
<%@ page import="javax.servlet.jsp.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.StringWriter" %>

<%@ page import="javax.xml.parsers.DocumentBuilder" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
<%@ page import="javax.xml.parsers.ParserConfigurationException" %>
<%@ page import="javax.xml.transform.OutputKeys" %>
<%@ page import="javax.xml.transform.Transformer" %>
<%@ page import="javax.xml.transform.TransformerException" %>
<%@ page import="javax.xml.transform.TransformerFactory" %>
<%@ page import="javax.xml.transform.TransformerFactoryConfigurationError"
%>
<%@ page import="javax.xml.transform.dom.DOMSource" %>
<%@ page import="javax.xml.transform.stream.StreamResult" %>

<%@ page import="org.w3c.dom.Document" %>
<%@ page import="org.w3c.dom.NodeList" %>
<%@ page import="org.xml.sax.SAXException" %>
<%@ include file="../common/common.jsp" %>
  <head>
    <title>Draw a Line</title>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta http-equiv="content-script-type" content="text/javascript">
    <meta http-equiv="content-style-type" content="text/css">
    <link href="../styles/globalStyles.css" rel="stylesheet" 
type="text/css">
    <link href="../styles/otherStyles.css" rel="stylesheet" type="text/css">

    <script language="javascript" type="text/javascript">
      function OnPageLoad()
      {
        parent.mapFrame.Refresh();
      }
    </script>
  </head>
  <body onLoad="OnPageLoad();">

    <%
      String sessionId = request.getParameter("SESSION");
      String mapName = request.getParameter("MAPNAME");
      String x0 = request.getParameter("x0");
      String y0 = request.getParameter("y0");
      String x1 = request.getParameter("x1");
      String y1 = request.getParameter("y1");

    try
    {
      // Initialize the Web Extensions and connect to the Server using
      // the Web Extensions session identifier stored in PHP
      // session state.

      MapGuideJavaApi.MgInitializeWebTier(webconfigFilePath);

      // Get the user information using the session id,
      // and set up a connection to the site server.
      
      MgUserInformation userInfo = new MgUserInformation(sessionId);
      MgSiteConnection siteConnection = new MgSiteConnection();
      siteConnection.Open(userInfo);
  
      // Get an instance of the required service(s).
      MgResourceService resourceService = (MgResourceService)
siteConnection.CreateService(MgServiceType.ResourceService);
      MgFeatureService featureService = (MgFeatureService)
siteConnection.CreateService(MgServiceType.FeatureService);
      
      MgMap map = new MgMap(); 
      map.Open(resourceService, mapName);
      
      //Constants for the new Layer
      String layerName = "Lines";
      String layerLegendLabel = "New Rectangle";
      String groupName = "Analysis";
      String groupLegendLabel = "Analysis";  
      
      // Does the temporary feature source already exist?
      // If not, create it
      String featureSourceName = "Session:" + sessionId +
"//TemporaryLines.FeatureSource";
      //String featureSourceName =
"Library://APITest/LineTest/TemporaryLines.FeatureSource";
      MgResourceIdentifier resourceIdentifier = new
MgResourceIdentifier(featureSourceName);
      
      //Wether or not the featureSource exists, it should always be deleted
      //Thats because when the user draws a new rectangle the old one should
vanish
      resourceService.DeleteResource(resourceIdentifier);
      
      // Create a temporary feature source to draw the lines on
      // Create a feature class definition for the new feature source
      MgClassDefinition classDefinition = new MgClassDefinition();
      classDefinition.SetName(layerName);
      classDefinition.SetDescription("Lines to display.");
      String geometryPropertyName="SHPGEOM";
      classDefinition.SetDefaultGeometryPropertyName(geometryPropertyName); 
          
      // Create an identity property
      MgDataPropertyDefinition identityProperty = new
MgDataPropertyDefinition("KEY");
      identityProperty.SetDataType(MgPropertyType.Int32);
      identityProperty.SetAutoGeneration(true);
      identityProperty.SetReadOnly(true); 
      // Add the identity property to the class definition
      classDefinition.GetIdentityProperties().Add(identityProperty);
      classDefinition.GetProperties().Add(identityProperty);
          
      // Create a name property
      MgDataPropertyDefinition nameProperty = new
MgDataPropertyDefinition("NAME");
      nameProperty.SetDataType(MgPropertyType.String); 
      // Add the name property to the class definition
      classDefinition.GetProperties().Add(nameProperty);
          
      // Create a geometry property
      MgGeometricPropertyDefinition geometryProperty = new
MgGeometricPropertyDefinition(geometryPropertyName);   
      geometryProperty.SetGeometryTypes(MgFeatureGeometricType.Surface);  
      // Add the geometry property to the class definition
      classDefinition.GetProperties().Add(geometryProperty); 
          
      // Create a feature schema
      MgFeatureSchema featureSchema = new MgFeatureSchema("SHP_Schema",
"Line schema");
      // Add the feature schema to the class definition
      featureSchema.GetClasses().Add(classDefinition);             
        
      // Create the feature source
      String wkt = map.GetMapSRS();
      MgCreateSdfParams sdfParams = new MgCreateSdfParams("spatial context",
wkt, featureSchema);  
      featureService.CreateFeatureSource(resourceIdentifier, sdfParams); 
      
      // Add the line to the feature source
      MgBatchPropertyCollection batchPropertyCollection = new
MgBatchPropertyCollection();
      MgPropertyCollection propertyCollection = MakeRect("Rect A", x0, y0,
x1, y1);
      batchPropertyCollection.Add(propertyCollection);
            
      // Add the batch property collection to the feature source
      MgInsertFeatures cmd = new MgInsertFeatures(layerName,
batchPropertyCollection); 
      MgFeatureCommandCollection featureCommandCollection = new
MgFeatureCommandCollection();
      featureCommandCollection.Add(cmd);
      
      // Execute the "add" commands
      featureService.UpdateFeatures(resourceIdentifier,
featureCommandCollection, false); 

      boolean layerExists = DoesLayerExist(layerName, map);
      if (!layerExists)
      {
        // Create a new layer which uses that feature source         
        // Create a line rule to stylize the lines
        String ruleLegendLabel = "Lines Rule";
        String filter = "";
        String color = "FF0000FF";
        //LayerDefinitionFactory factory = new LayerDefinitionFactory();
        String lineRule = createLineRule(ruleLegendLabel, filter, color);
                
        // Create a line type style
        String lineTypeStyle = createLineTypeStyle(lineRule);
        
        // Create a scale range
        String minScale = "0";
        String maxScale = "1000000000000";
        String lineScaleRange = createScaleRange(minScale, maxScale,
lineTypeStyle);   
      
        // Create the layer definiton
        String featureName = "SHP_Schema:Lines";
        String geometry = "SHPGEOM";
        String layerDefinition = createLayerDefinition(featureSourceName,
featureName, geometry, lineScaleRange);
        
        //---------------------------------------------------//  
        // Add the layer to the map
        MgLayer newLayer = add_layer_definition_to_map(layerDefinition,
layerName, layerLegendLabel, sessionId, resourceService, map);
        // Add the layer to a layer group
        add_layer_to_group(newLayer, groupName, groupLegendLabel, map);
      }

      // Turn on the visibility of this layer.
      // (If the layer does not already exist in the map, it will be visible
by default when it is added.
      // But if the user has already run this script, he or she may have set
the layer to be invisible.)
      MgLayerCollection layerCollection = map.GetLayers();
      if (layerCollection.Contains(layerName)) 
      {
        MgLayer linesLayer = (MgLayer) layerCollection.GetItem(layerName);
        linesLayer.SetVisible(true);
      }
      
      MgLayerGroupCollection groupCollection = map.GetLayerGroups();
      if (groupCollection.Contains(groupName))
      {
        MgLayerGroup analysisGroup = groupCollection.GetItem(groupName);
        analysisGroup.SetVisible(true);
      }    
      
      //---------------------------------------------------//
      //  Save the map back to the session repository
      String sessionIdName = "Session:" + sessionId + "//" + mapName +
".Map";
      //String sessionIdName =
"Library://APITest/LineTest/TemporaryLines.Map";
      MgResourceIdentifier sessionResourceID = new
MgResourceIdentifier(sessionIdName);
      sessionResourceID.Validate();
      map.Save(resourceService, sessionResourceID);
    }
    catch (MgLayerNotFoundException e)
    {
      out.println("<p>Layer not found</p>");
    }
    catch (MgObjectNotFoundException e)
    {
      out.println("<p>Layer not found</p>");
    }
    catch (MgException e)
    {
      out.println(e.GetMessage());
      out.println(e.GetDetails());
    }
  %>
<%!
private static boolean DoesLayerExist(String layerName, MgMap map) throws
MgException
{
        MgLayerCollection layerCollection = map.GetLayers();   
        return(layerCollection.Contains(layerName) ? true : false ) ;
}

private static MgPropertyCollection MakeRect(String name, String x0, String
y0 , String x1, String y1) throws MgException
{
        MgPropertyCollection propertyCollection = new MgPropertyCollection();

        MgStringProperty nameProperty = new MgStringProperty("NAME", name);
        propertyCollection.Add(nameProperty);
          
        MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); 
        
        MgMultiLineString mls = createMultiLineStringXY(x0, y0, x1, y1);
        
        MgByteReader geometryByteReader = agfReaderWriter.Write(mls); 
        MgGeometryProperty geometryProperty = new MgGeometryProperty("SHPGEOM",
geometryByteReader);
        propertyCollection.Add(geometryProperty);
          
        return propertyCollection;
}

private static MgMultiLineString createMultiLineStringXY(String x0, String
y0, String x1, String y1) throws MgException
{
        MgGeometryFactory geometryFactory = new MgGeometryFactory();
        
    MgLineStringCollection lines = new MgLineStringCollection();
    //left
    lines.Add(createLineStringXY(x0, y0, x0, y1));
    //right
    lines.Add(createLineStringXY(x1, y0, x1, y1));
        //up
    lines.Add(createLineStringXY(x0, y0, x1, y0));
        //down
    lines.Add(createLineStringXY(x0, y1, x1, y1));
  
    return geometryFactory.CreateMultiLineString(lines);
}


private static MgLineString createLineStringXY(String x0, String y0, String
x1, String y1) throws MgException
{
        double x0d = Double.valueOf(x0).doubleValue();
        double y0d = Double.valueOf(y0).doubleValue();
        double x1d = Double.valueOf(x1).doubleValue();
        double y1d = Double.valueOf(y1).doubleValue();

        MgGeometryFactory geometryFactory = new MgGeometryFactory();
    MgCoordinateCollection coords = new MgCoordinateCollection();
    coords.Add(geometryFactory.CreateCoordinateXY(x0d, y0d));
    coords.Add(geometryFactory.CreateCoordinateXY(x1d, y1d));
    return geometryFactory.CreateLineString(coords);
}


private static MgLayer add_layer_definition_to_map(String layerDefinition,
String layerName, String layerLegendLabel, String sessionId,
MgResourceService resourceService, MgMap map) throws MgException {
        //Adds the layer definition (XML) to the map.
        //Returns the layer.
        // Save the new layer definition to the session repository
        //MgByteSource(ByteArray, Int) -> layerDefinition.getBytes()
        MgByteSource byteSource = new MgByteSource(layerDefinition.getBytes(),
layerDefinition.length());
        byteSource.SetMimeType(MgMimeType.Xml);
        MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" +
sessionId + "//" + layerName + ".LayerDefinition");
        //MgResourceIdentifier resourceID = new
MgResourceIdentifier("Library://APITest/LineTest/TemporaryLines.LayerDefinition");
        resourceService.SetResource(resourceID, byteSource.GetReader(), null);

        MgLayer newLayer = add_layer_resource_to_map(resourceID, 
resourceService,
layerName, layerLegendLabel, map);
        return newLayer;
}

private static MgLayer add_layer_resource_to_map(MgResourceIdentifier
layerResourceID, MgResourceService resourceService, String layerName, String
layerLegendLabel, MgMap map) throws MgException
        //Adds a layer defition (which can be stored either in the Library or a
session repository) to the map.
        //Returns the layer.
        {
                MgLayer newLayer = new MgLayer(layerResourceID, 
resourceService);  
                
                //Add the new layer to the map's layer collection
                newLayer.SetName(layerName);
                newLayer.SetVisible(true);
                newLayer.SetLegendLabel(layerLegendLabel);
                newLayer.SetDisplayInLegend(true);
                MgLayerCollection layerCollection = map.GetLayers(); 
                if (!layerCollection.Contains(layerName) )
                        {
                        // Insert the new layer at position 0 so it is at the 
top of the drawing
order
                        layerCollection.Insert(0, newLayer); 
                }
                return newLayer;
        }

public static void add_layer_to_group(MgLayer layer, String layerGroupName,
String layerGroupLegendLabel, MgMap map) throws MgException
        //Adds a layer to a layer group. If necessary, it creates the layer 
group.
        {
        //Get the layer group
        MgLayerGroupCollection layerGroupCollection = map.GetLayerGroups();
        MgLayerGroup layerGroup = null;
        if (layerGroupCollection.Contains(layerGroupName))
        {
                layerGroup = layerGroupCollection.GetItem(layerGroupName);
        }
        else
        {
                // It does not exist, so create it
                layerGroup = new MgLayerGroup(layerGroupName); 
                layerGroup.SetVisible(true);
                layerGroup.SetDisplayInLegend(true);
                layerGroup.SetLegendLabel(layerGroupLegendLabel);
                layerGroupCollection.Add(layerGroup); 
        }
        
        //Add the layer to the group
        layer.SetGroup(layerGroup);  
}
//Creates line rule
//Parameters:
//$color - color code for the line
//$legendLabel - string for the legend label
//$filter - filter string
public static String createLineRule(String legendLabel, String filter,
String color) throws ParserConfigurationException, SAXException, IOException
{
         String linerule =
readFileAsString("c:\\Programme\\_gis\\OSGeo\\MapGuide\\Web\\www\\viewerfiles\\linerule.templ");
         
         StringBuilder sb = new StringBuilder();
         Formatter formatter = new Formatter(sb, Locale.GERMANY);
         formatter.format(linerule, legendLabel, filter, color);
         linerule = formatter.toString();

         return linerule;
}

//Creates LineTypeStyle
//Parameters:
//$lineRules - call CreateLineRule to create line rules
public static String createLineTypeStyle(String lineRules) throws
ParserConfigurationException, SAXException, IOException
{   
         String linestyle =
readFileAsString("c:\\Programme\\_gis\\OSGeo\\MapGuide\\Web\\www\\viewerfiles\\linetypestyle.templ");
            
         StringBuilder sb = new StringBuilder();
         Formatter formatter = new Formatter(sb, Locale.GERMANY);
         formatter.format(linestyle, lineRules);
        linestyle = formatter.toString();
         
 return linestyle;
}
//Creates ScaleRange
//Parameterss
//$minScale - minimum scale
//$maxScale - maximum scale
//$typeStyle - use one CreateAreaTypeStyle, CreateLineTypeStyle, or
CreatePointTypeStyle
public static String createScaleRange(String minScale, String maxScale,
String typeStyle) throws ParserConfigurationException, SAXException,
IOException
{    
         String scaleRange =
readFileAsString("c:\\Programme\\_gis\\OSGeo\\MapGuide\\Web\\www\\viewerfiles\\scalerange.templ");
       
         StringBuilder sb = new StringBuilder();
         Formatter formatter = new Formatter(sb, Locale.GERMANY);
         formatter.format(scaleRange, minScale, maxScale, typeStyle);
         scaleRange = formatter.toString();
         
  return scaleRange;
}

//Creates a layer definition
//$resourceId - resource identifier for the new layer
//featureClass - the name of the feature class
//$geometry - the name of the geometry
//$featureClassRange - use CreateScaleRange to define it.
public static String createLayerDefinition(String resourceId, String
featureClass, String geometry, String featureClassRange) throws
ParserConfigurationException, SAXException, IOException
{           
         String layerDef =
readFileAsString("c:\\Programme\\_gis\\OSGeo\\MapGuide\\Web\\www\\viewerfiles\\layerdefinition.templ");
          
         StringBuilder sb = new StringBuilder();
         Formatter formatter = new Formatter(sb, Locale.GERMANY);
         formatter.format(layerDef, resourceId, featureClass, geometry,
featureClassRange);
         layerDef = formatter.toString();
          return layerDef;
}

private static String readFileAsString(String filePath) throws
java.io.IOException{
    byte[] buffer = new byte[(int) new File(filePath).length()];
    BufferedInputStream f = new BufferedInputStream(new
FileInputStream(filePath));
    f.read(buffer);
    return new String(buffer);
}
%>
</body>
</html>


maybe this is helpful to somebody :)

And before I forget it, I have some unsolved MGOS problems here:
http://n2.nabble.com/SetSelectionXML-Problem-Selection-and-Zoom-to-selected-Feature-td4585892.html
and here:
http://n2.nabble.com/CoordinateSystem-Problems-with-Data-from-WMS-EPSG-31468-and-2398-td4461491.html
-- 
View this message in context: 
http://n2.nabble.com/Digitizing-Redlining-Draw-a-Rectangle-composed-from-Lines-Partly-Java-implemention-of-LayerDefinitioy-tp4638735p4638735.html
Sent from the MapGuide Users mailing list archive at Nabble.com.
_______________________________________________
mapguide-users mailing list
[email protected]
http://lists.osgeo.org/mailman/listinfo/mapguide-users

Reply via email to