├── .gitignore ├── LICENSE ├── README.md ├── book ├── pom.xml └── src │ └── main │ └── latex │ ├── common │ └── images │ │ ├── duty_calls.png │ │ ├── map_projections.png │ │ └── projections2.png │ └── geotools-cookbook │ ├── distance.tex │ ├── filters.tex │ ├── geotools-cookbook.tex │ ├── input.tex │ ├── introduction.tex │ ├── output.tex │ ├── postamble.tex │ ├── preamble.tex │ ├── preface.tex │ ├── projections.tex │ ├── refs.bib │ └── styling.tex ├── data ├── TQ19.asc ├── coast_ln_polyline.avl ├── coast_ln_polyline.dbf ├── coast_ln_polyline.prj ├── coast_ln_polyline.qix ├── coast_ln_polyline.shp ├── coast_ln_polyline.shx ├── coastline.sld ├── ne_10m_admin_0_countries.README.html ├── ne_10m_admin_0_countries.dbf ├── ne_10m_admin_0_countries.prj ├── ne_10m_admin_0_countries.qix ├── ne_10m_admin_0_countries.shp ├── ne_10m_admin_0_countries.shx ├── states.dbf ├── states.prj ├── states.qix ├── states.shp ├── states.shx ├── states_conic.dbf ├── states_conic.fix ├── states_conic.prj ├── states_conic.shp ├── states_conic.shx ├── world.200412.3x21600x10800.jpg └── world.200412.3x21600x10800.jpw ├── modules ├── distances │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── ianturton │ │ └── cookbook │ │ └── distances │ │ ├── AutoProjection.java │ │ ├── OrthodromicDistance.java │ │ └── OrthodromicDistance2.java ├── filters │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── ianturton │ │ └── cookbook │ │ └── filters │ │ ├── PointInPolygon.java │ │ └── QueryGrid.java ├── input │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── ianturton │ │ └── cookbook │ │ └── input │ │ └── SaveMapAsImage.java ├── output │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── ianturton │ │ └── cookbook │ │ └── output │ │ ├── ExportGeometries.java │ │ ├── MapWithGrid.java │ │ ├── SaveMapAsImage.java │ │ └── WriteShapefile.java ├── pom.xml ├── projections │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── ianturton │ │ └── cookbook │ │ └── projections │ │ ├── QueryEPSG.java │ │ ├── ReprojectShapeFile.java │ │ └── Tissot.java ├── quickstart │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── org │ │ │ └── geotools │ │ │ └── tutorial │ │ │ └── quickstart │ │ │ ├── Quickstart.java │ │ │ ├── QuickstartCache.java │ │ │ └── QuickstartNotes.java │ │ └── main │ │ ├── java │ │ └── org │ │ │ └── geotools │ │ │ ├── api │ │ │ ├── APIExamples.java │ │ │ ├── DataStoreExamples.java │ │ │ └── validation │ │ │ │ └── ValidationExamples.java │ │ │ ├── brewer │ │ │ └── BrewerExamples.java │ │ │ ├── coverage │ │ │ └── CoverageExamples.java │ │ │ ├── cql │ │ │ ├── CQLExamples.java │ │ │ ├── DataExamples.java │ │ │ ├── ECQLExamples.java │ │ │ └── Utility.java │ │ │ ├── data │ │ │ ├── DataExamples.java │ │ │ ├── SimpleFeatureStoreExamples.java │ │ │ └── property │ │ │ │ ├── PropertyAttributeReader.java │ │ │ │ ├── PropertyDataStore.java │ │ │ │ ├── PropertyDataStoreFactory.java │ │ │ │ ├── PropertyExamples.java │ │ │ │ └── PropertyFeatureReader.java │ │ │ ├── geometry │ │ │ └── GeometryExamples.java │ │ │ ├── graph │ │ │ └── GraphExamples.java │ │ │ ├── grid │ │ │ ├── GridExamples.java │ │ │ └── IntersectionBuilder.java │ │ │ ├── jdbc │ │ │ └── JDBCExamples.java │ │ │ ├── jts │ │ │ ├── JTSExamples.java │ │ │ └── SnapToLine.java │ │ │ ├── main │ │ │ ├── FilterExamples.java │ │ │ ├── JoinExample.java │ │ │ └── MainExamples.java │ │ │ ├── metadata │ │ │ ├── Example.java │ │ │ └── MetadataExamples.java │ │ │ ├── opengis │ │ │ ├── FeatureExamples.java │ │ │ ├── FilterExamples.java │ │ │ └── StyleExamples.java │ │ │ ├── po │ │ │ ├── Items.java │ │ │ ├── ObjectFactory.java │ │ │ ├── PurchaseOrderType.java │ │ │ ├── USAddress.java │ │ │ ├── bindings │ │ │ │ ├── ItemsBinding.java │ │ │ │ ├── Items_itemBinding.java │ │ │ │ ├── PO.java │ │ │ │ ├── POConfiguration.java │ │ │ │ ├── PurchaseOrderTypeBinding.java │ │ │ │ ├── SKUBinding.java │ │ │ │ └── USAddressBinding.java │ │ │ └── package-info.java │ │ │ ├── process │ │ │ └── FeatureProcessExamples.java │ │ │ ├── referencing │ │ │ └── ReferencingExamples.java │ │ │ ├── render │ │ │ ├── GenerateSVG.java │ │ │ ├── SplatMarkFactory.java │ │ │ ├── StyleConverter.java │ │ │ └── StyleExamples.java │ │ │ ├── swing │ │ │ ├── JExampleWizard.java │ │ │ └── JMapPaneExamples.java │ │ │ ├── tutorial │ │ │ ├── crs │ │ │ │ └── CRSLab.java │ │ │ ├── datastore │ │ │ │ ├── CSVDataStore.java │ │ │ │ ├── CSVFeatureReader.java │ │ │ │ └── CSVFeatureSource.java │ │ │ ├── feature │ │ │ │ └── Csv2Shape.java │ │ │ ├── filter │ │ │ │ └── QueryLab.java │ │ │ ├── function │ │ │ │ ├── AbstractFunction.java │ │ │ │ ├── ExampleFinder.java │ │ │ │ ├── ExampleFunctionFactory.java │ │ │ │ ├── ExampleFunctionFactory2.java │ │ │ │ └── SnapFunction.java │ │ │ ├── graph │ │ │ │ └── Tiger.java │ │ │ ├── package-info.java │ │ │ ├── process │ │ │ │ ├── BufferFactory.java │ │ │ │ ├── BufferFeatureCollectionFactory.java │ │ │ │ ├── BufferFeatureCollectionProcess.java │ │ │ │ ├── BufferProcess.java │ │ │ │ ├── ProcessExample.java │ │ │ │ └── ProcessTutorial.java │ │ │ ├── quickstart │ │ │ │ ├── Quickstart.java │ │ │ │ ├── QuickstartCache.java │ │ │ │ └── QuickstartNotes.java │ │ │ ├── raster │ │ │ │ └── ImageLab.java │ │ │ ├── style │ │ │ │ ├── SelectionLab.java │ │ │ │ └── StyleLab.java │ │ │ └── wms │ │ │ │ └── WMSLab.java │ │ │ └── xml │ │ │ ├── FilterXMLExamples.java │ │ │ ├── GML2Schema.java │ │ │ ├── GMLExamples.java │ │ │ ├── GMLParsing.java │ │ │ ├── TestSchema.java │ │ │ └── YourCode.java │ │ └── resources │ │ ├── META-INF │ │ └── services │ │ │ └── org.geotools.process.ProcessFactory │ │ └── org │ │ └── geotools │ │ ├── cql │ │ └── usa-geometry.wkt │ │ ├── grid │ │ ├── oz.dbf │ │ ├── oz.fix │ │ ├── oz.prj │ │ ├── oz.qix │ │ ├── oz.shp │ │ └── oz.shx │ │ └── xml │ │ ├── states.xml │ │ └── states.xsd └── styling │ ├── pom.xml │ └── src │ └── main │ └── java │ └── org │ └── ianturton │ └── cookbook │ └── styling │ ├── FontManagement.java │ └── TwoAttributes.java └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | .gitignore 3 | 4 | # Mobile Tools for Java (J2ME) 5 | .mtj.tmp/ 6 | 7 | # Package Files # 8 | *.jar 9 | *.war 10 | *.ear 11 | 12 | #latex stuff 13 | 14 | *.aux 15 | *.toc 16 | *.log 17 | *.lol 18 | *.out 19 | 20 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 21 | hs_err_pid* 22 | 23 | #eclipse files 24 | .project 25 | .classpath 26 | .settings/* 27 | *.prefs 28 | target/* 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | geotools-cookbook 2 | ================= 3 | 4 | This is a draft of the text and code for a cookbook that aims to introduce new users to the tricks and tips that make using GeoTools more fun. 5 | -------------------------------------------------------------------------------- /book/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.ianturton 8 | cookbook 9 | 1.0 10 | 11 | com.ianturton.cookbook 12 | book 13 | 1.0-SNAPSHOT 14 | 15 | 16 | codehaus 17 | Maven Codehaus repository 18 | http://repository.codehaus.org/ 19 | 20 | 21 | codehaus-snapshots 22 | Maven Codehaus snapshot repository 23 | http://snapshots.repository.codehaus.org/ 24 | 25 | 26 | 27 | 28 | maven-latex-plugin-repo 29 | http://akquinet.github.com/maven-latex-plugin/maven2/ 30 | 31 | true 32 | 33 | 34 | 35 | 36 | 37 | 38 | ${basedir}/src/main/latex/geotools-cookbook 39 | true 40 | 41 | **/*.tex 42 | **/images/* 43 | 44 | 45 | 46 | ${basedir}/src/main/latex/common 47 | 48 | **/images/* 49 | 50 | 51 | 52 | 53 | 54 | 55 | de.akquinet.maven 56 | maven-latex-plugin 57 | 1.1 58 | 59 | 60 | compile 61 | 62 | latex 63 | 64 | 65 | 66 | 67 | 68 | 69 | 71 | ${basedir}/target/classes 72 | 74 | . 75 | 77 | m2latex 78 | 79 | true 80 | 81 | 82 | 83 | pdflatex 84 | 85 | bibtex 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | org.eclipse.m2e 95 | lifecycle-mapping 96 | 1.0.0 97 | 98 | 99 | 100 | 101 | 102 | 103 | de.akquinet.maven 104 | 105 | 106 | maven-latex-plugin 107 | 108 | 109 | [1.1,) 110 | 111 | 112 | latex 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /book/src/main/latex/common/images/duty_calls.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/book/src/main/latex/common/images/duty_calls.png -------------------------------------------------------------------------------- /book/src/main/latex/common/images/map_projections.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/book/src/main/latex/common/images/map_projections.png -------------------------------------------------------------------------------- /book/src/main/latex/common/images/projections2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/book/src/main/latex/common/images/projections2.png -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/distance.tex: -------------------------------------------------------------------------------- 1 | \chapter{Distances and GeoFencing} 2 | 3 | 4 | 5 | \lstinputlisting[firstline=21,firstnumber=21,caption=How to calculate the distance between two points.] 6 | {distances/src/main/java/org/ianturton/cookbook/distances/OrthodromicDistance.java} 7 | \label{distance1} 8 | -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/filters.tex: -------------------------------------------------------------------------------- 1 | \chapter{Querying, Filtering and Sorting: finding what you need}\label{filters} 2 | \section{Creating and running a query} 3 | \section{Filters} 4 | \subsection{OGC Filters} 5 | \subsection{CQL Filters} 6 | \section{Sorting your results} -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/geotools-cookbook.tex: -------------------------------------------------------------------------------- 1 | \RequirePackage[l2tabu, orthodox]{nag} 2 | %\documentclass[a4paper]{tufte-book} 3 | \documentclass{scrbook} 4 | % leave this last 5 | \usepackage[bookmarksdepth=subsection,hidelinks]{hyperref} 6 | \usepackage{scrhack} 7 | \usepackage{todonotes} 8 | %\usepackage[printonlyused,withpage]{acronym} 9 | \usepackage{acronym} 10 | \usepackage{listings} 11 | \usepackage{graphicx} 12 | \usepackage{siunitx} 13 | \usepackage{caption} 14 | \usepackage{xspace} 15 | \usepackage{microtype} 16 | \usepackage{cleveref} 17 | \usepackage[comma,authoryear]{natbib} 18 | \usepackage{spverbatim} 19 | \usepackage{ccicons} 20 | 21 | % fix the kerning in GeoTools to look nicer (to me) 22 | \newcommand{\GeoTools}{Geo\kern -.15em T\kern -.15em ools\xspace} 23 | \DeclareRobustCommand\Hazard[1][red]{\makebox[0pt][r]{\color{#1}\huge\Biohazard\hspace{2em}}} 24 | \title{\GeoTools Cookbook} 25 | \author{Ian Turton} 26 | 27 | % define how the listings will look 28 | \lstset{ 29 | basicstyle=\footnotesize\ttfamily,numbers=left, numberstyle=\tiny, numbersep=5pt, 30 | frame=single, 31 | breaklines=true, 32 | postbreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\color{red}\hookrightarrow\space}} 33 | } 34 | \lstset{tabsize=2} 35 | \lstloadlanguages{java} 36 | 37 | %and finally start the book! 38 | 39 | \begin{document} 40 | \maketitle 41 | \tableofcontents 42 | \lstlistoflistings 43 | \clearpage 44 | 45 | \include{preface} 46 | \include{introduction} 47 | \include{input} 48 | \include{output} 49 | \include{filters} 50 | \include{styling} 51 | \include{projections} 52 | \include{distance} 53 | \todo{add the rest of the chapters as includes} 54 | \chapter{Going Further} 55 | \bibliographystyle{plainnat} 56 | \bibliography{refs} 57 | % this contains the acronyms - which for some reason doesn't work at the front. 58 | \include{postamble} 59 | \todo{remove this list when finished} 60 | \listoftodos 61 | \end{document} 62 | -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/input.tex: -------------------------------------------------------------------------------- 1 | \chapter{Input, getting the data in to \GeoTools}\label{input} 2 | \section{Vector Datasets}\label{vector} 3 | \section{Raster Datasets}\label{raster} -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/introduction.tex: -------------------------------------------------------------------------------- 1 | \chapter{Introduction}\label{introduction} 2 | 3 | \section{Getting Started} 4 | I'm going to make the assumption that as a Java developer who already have a favourite set of development tools and are fairly happy in how to use them. 5 | 6 | \subsection{Maven} 7 | One of the things that often worries or confuses new users of the \GeoTools library is it's use of the Maven build system. So people will pop up on the mailing list asking why they have a missing method when trying to compile one of the tutorial programs, this is almost always because they have not installed and used maven. 8 | To get anywhere with \GeoTools you will need to have \href{http://maven.apache.org/}{Apache Maven} installed on your machine. Maven is an automated build management tool, once upon a time programmers used to use \texttt{make} to control how a program was built, it ``knew'' how to turn files ending in \texttt{.c} or \texttt{.f} into \texttt{.o} files and with some hints from the developer how to put those files together into an executable file. When your program consisted of 10's of files this was fine but things soon broke down. The \texttt{C} and \texttt{C++} communities started to extend this system with \texttt{autoconfig} and \texttt{cmake} to automatically build a \texttt{make} file for you. The Java community (with it's love of XML) went to \href{http://ant.apache.org/}{\texttt{ant}} which was more aware of how Java programs went together. But over time \texttt{ant} build files became hard to manage, eventually maven was born. It favours convention over configuration, or more plainly if you put your files in the right place maven will find and build them. Maven also simplifies dependency management, you simply specify the the jar that you need to add to make your program work and maven will go off, find and download not just that jar file but also the jars that it depends on. We will return to this later in this chapter but for now make sure Maven is installed on your machine. If you use Eclipse or Netbeans as your \ac{IDE} then maven is already built in, but you might want to download the standalone version anyway. 9 | 10 | \section{Hello World} 11 | 12 | There is an \href{http://en.wikipedia.org/wiki/\%22Hello,_world!\%22_program}{unwritten law} that any programming book must include a Hello World program. This is because it is normally easy to print out a simple string which means the beginning programmer can concentrate on the form of the program rather than it's actual algorithm. Since this is a book for geographers/programmers we will start with a program that displays a map of the world (rather than a string). 13 | 14 | A slightly trimmed version of the code you will need is shown in \cref{HelloWorld}, the full program is about 50 lines long. \todo{Add note on where to download code samples} \Cref{pom} shows the maven pom file you will need compile it, you'll notice that it is about the same length as the program itself\footnote{So may be there is some truth to what the maven haters say}. So to display a map we first need to compile the program \verb!mvn compile! -- you'll see lots of messages scroll across the screen telling you about the jar files that maven has fetched for you. If that all goes well then you can use \verb!mvn exec:java! to run the program. 15 | 16 | \lstinputlisting[firstline=29,firstnumber=29,lastline=54,caption={Hello World GIS style},label=HelloWorld]{quickstart/src/main/java/org/geotools/tutorial/quickstart/Quickstart.java} 17 | 18 | \lstinputlisting[caption={Maven Pom file}, label=pom, language=xml]{quickstart/pom.xml} 19 | 20 | -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/output.tex: -------------------------------------------------------------------------------- 1 | \chapter{Output} 2 | \todo{think of a better title} 3 | 4 | \section{Introduction} 5 | Once you have your data set up the way you would like you will want 6 | to export it in some sort of form that allows you to use it. 7 | 8 | \section{Working with Geometries}\label{geoms} 9 | \todo{decide where this should go} 10 | Within \GeoTools geometries are represented by \ac{JTS} Geometries that contain the actual positions as Coordinates. 11 | Sometimes when exporting geometries you would like to produce a plain text string that represents the geometry, if for no other reason than it's easier to see what is happening than starting up a debugger. 12 | This sort of interoperability issue comes up often enough that there is a standard way of doing it (well two in fact). The most common format is \ac{WKT}. 13 | 14 | \lstinputlisting[firstline=38,firstnumber=38,lastline=40,label=wkt,caption={Exporting WKT from a geometry}]{output/src/main/java/org/ianturton/cookbook/output/ExportGeometries.java} 15 | 16 | \Cref{wkt} shows just how simple this process is. This will produce output like \cref{wktoutput}. WKT is kept deliberately simple so that writing a program that can read it in or write it out is easy. The standard was originally written by the \ac{OGC} as part of Simple Feature specification, it is now defined in the ISO 13249 ``Information technology -- Database languages -- SQL multimedia and application packages -- Part 3: Spatial'' standard. 17 | 18 | \begin{figure}[h] 19 | \begin{spverbatim} 20 | POINT (10.1 22.2) 21 | LINESTRING (1 1, 2 3, 4.4 5.2) 22 | POLYGON ((1 1, 2 3, 4.4 5.2, 1 1)) 23 | MULTIPOLYGON (((1 1, 2 3, 4.4 5.2, 1 1)), 24 | ((10 10, 20 30, 40.4 50.2, 10 10))) 25 | \end{spverbatim} 26 | \caption{Some examples of WKT}\label{wktoutput} 27 | \end{figure} 28 | 29 | One important point to notice is that \spverb!POLYGON! has two parenthesis at the start and end, this allows you to specify holes in your polygon (think islands in a lake) which are represented like \spverb!POLYGON ((35 10, 45 45, 15 40, 10 20, 35 10),(20 30, 35 35, 30 20, 20 30))!. 30 | 31 | \section{Creating an Image of the Map} 32 | Assuming that you have created a map that you like with the correct styling and area of interest 33 | set then you might want to produce a picture of it. \Cref{save} shows how to do this. 34 | 35 | \lstinputlisting[firstline=27,firstnumber=27,label=save,caption=Save a picture of the map.]{output/src/main/java/org/ianturton/cookbook/output/SaveMapAsImage.java} 36 | 37 | \section{Create a New Shapefile} 38 | 39 | \lstinputlisting[firstline=40,firstnumber=40,label=shapefile,caption=Save a shapefile.]{output/src/main/java/org/ianturton/cookbook/output/WriteShapefile.java} 40 | 41 | -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/postamble.tex: -------------------------------------------------------------------------------- 1 | \cleardoublepage 2 | \chapter*{Acronyms} 3 | \begin{acronym}[XXXXX] 4 | \acro{OGC}{Open Geospatial Consortium} 5 | \acro{JTS}{Java Topology Suite} 6 | \acro{WKT}{Well Known Text} 7 | \acro{WKB}{Well Known Binary} 8 | \acro{ISO}{International Standards Organization} 9 | \acro{CCG}{Centre for Computational Geography} 10 | \acro{GIS}{Geographic Information System} 11 | \acro{TOPP}{The Open Planning Project} 12 | \acro{IDE}{Integrated Development Environment} 13 | \end{acronym} 14 | -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/preamble.tex: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/book/src/main/latex/geotools-cookbook/preamble.tex -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/preface.tex: -------------------------------------------------------------------------------- 1 | \chapter{Preface} 2 | \section{About this book} 3 | This book is a gentle introduction to the \GeoTools library. It is aimed at developers who have a geographic problem that they want to solve in Java. 4 | 5 | \section{About the author} 6 | I'm a programmer and while waiting for my code to compile I hang out on the \href{http://gis.stackexchange.com/}{GIS StackExchange site} answering questions as \texttt{iant}. Over the past 4 years I've answered more than 600 questions, adding this experience to the issues I helped students with when I worked at Leeds University and Pennsylvania State University, I think I've got a pretty good idea of where people go wrong when starting out with geography and geographic programs. The aim of this book is to distil some of my knowledge in to a form I can point people to, which should save me some typing in the future. 7 | 8 | However as XKCD points out in \cref{xkcd-duty} it's unlikely to solve all my problems. 9 | 10 | 11 | \begin{figure}[htbp] 12 | {\centering 13 | \includegraphics{images/duty_calls} 14 | \caption{Why we need this book?\\ \ccbync~\href{http://xkcd.com/386/}{XKCD}} 15 | \label{xkcd-duty} 16 | } 17 | \end{figure} 18 | 19 | \section{Who is this book for?} 20 | You are a Java developer who has written a number of complex programs already, you know how to set up your development environment whether it is an \ac{IDE} or a command line and text editor. You are happy using Maven to manage your code (or at least willing to learn) and you have a interest in geographic problems (or your boss has). However, you are smart and you don't want to have to write a whole geographic library for yourself from scratch. You have no time or energy to look up the Shapefile white paper \citep{ESRI1997} to see how to read your data in, or work out the projection needed to make the map equal area. 21 | 22 | So to make your life easier you've picked an existing library but now you have to learn how that works. This book will help you solve common problems using the \GeoTools library. 23 | 24 | The joy of Java programming is that it doesn't matter if you use a Linux machine, a windows box or even a Mac. But beware many parts of the \GeoTools library depend on the AWT and the Java Service Provider mechanism neither of which work on Android devices at the time of writing, so if you want to write Android applications you will need to find another library. That's not to say you can't take some of the code and techniques shown here on Android just that there is a fairly good chance that it will not work as is. 25 | 26 | \section{A brief history of \GeoTools} 27 | Once upon a time, when I was a newish (and keen) post--doctoral researcher in the \ac{CCG} at the University of Leeds there was a younger (and keener) Master's student call James Macgill who wanted to investigate swarms of agents moving around a map. The current state of the art \ac{GIS} system was unable to do more than draw a simple map. The ``obvious'' solution was to write our own \ac{GIS} system and so \GeoTools was born. Version 1 of the library was really intended for internal use only but news of leaked out and people (like \ac{TOPP} started to use it). Overtime a user community developed, and then they started wanting bug fixes and new features! It was terrible, as by now both of us had other jobs to do and very little spare time for \GeoTools. At the same time it was becoming apparent that there were some design choices that would make extending the library any further difficult, so we took the only sensible course of action and abandoned the project. We then replaced \GeoTools--1 with \GeoTools--2, which was redesigned to incorporate all (or at least some of) the lessons we had learned in \GeoTools--1. 28 | 29 | \GeoTools--2 was built on a generic feature definition, to start with it only supported \ac{OGC} Simple Features, but later when users needed complex features it was (relatively) easy to add support for them. We also switched from using Ant to Maven to manage the build and started to produce modular jar files to allow users to pick and choose the parts they wanted to use. We also recruited a bunch of new developers from \ac{TOPP} and Refractions Research who were building the GeoServer WMS Server and the UDig editor respectively. 30 | 31 | After a while it became clear that \GeoTools--3 was never going to arrive (or it is a long way in the future) so the version of the \GeoTools library moved from 2.7.x to 8.0. This book has been developed against version ${geotools.version} of the library. 32 | -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/projections.tex: -------------------------------------------------------------------------------- 1 | \chapter{Projections} 2 | \section{Introduction} 3 | Why we need to worry about projections? I'm going to let you in on a geographic secret ``the world is round'' -- sadly most of the maps we draw are \textbf{flat}. This leaves us with a problem, as anyone who has ever tried to gift wrap a globe knows, it's hard to make a curved surface and a flat sheet match up. 4 | 5 | As the ever helpful XKCD points out in \cref{xkcd-projections} there are a lot of projections. 6 | 7 | \todo{make this image narrower} 8 | \begin{figure}[htbp] 9 | {% 10 | \setlength{\fboxsep}{0pt}% 11 | \setlength{\fboxrule}{1pt}% 12 | \fbox{\includegraphics[width=\textwidth]{images/projections2}}% 13 | }% 14 | 15 | \caption{A quick introduction to projections\\ \ccbync~\href{http://xkcd.com/977/}{XKCD}} 16 | \label{xkcd-projections} 17 | \end{figure} 18 | 19 | Before you go too deep into the world of projections you should download and (at least) skim \cite{snyder}. This will give you access to all the helpful maths that \GeoTools encodes for you (or if you are unlucky that you will need to add a new projection to the library). 20 | 21 | \section{How to reproject features in \GeoTools} 22 | \section{How to choose a ``good'' projection} -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/refs.bib: -------------------------------------------------------------------------------- 1 | % This file was created with JabRef 2.10. 2 | % Encoding: Cp1252 3 | 4 | 5 | @Book{Peterson2012, 6 | Title = {Cartographer's toolkit}, 7 | Author = {Gretchen N. Peterson}, 8 | Publisher = {PetersonGIS}, 9 | Year = {2012}, 10 | 11 | Owner = {ian.turton}, 12 | Timestamp = {2014.11.18} 13 | } 14 | 15 | @TechReport{snyder, 16 | Title = {Map Projections -- A Working Manual}, 17 | Author = {John P. Snyder}, 18 | Institution = {U.S. Geological Survey}, 19 | Year = {1987}, 20 | Number = {1395}, 21 | Type = {Professional Paper}, 22 | 23 | Owner = {ian.turton}, 24 | Timestamp = {2014.11.17}, 25 | Url = {http://pubs.usgs.gov/pp/1395/report.pdf} 26 | } 27 | 28 | -------------------------------------------------------------------------------- /book/src/main/latex/geotools-cookbook/styling.tex: -------------------------------------------------------------------------------- 1 | \chapter{Styling: How to make a pretty map.}\label{styling} 2 | \section{Introduction} 3 | Try to read \cite{Peterson2012} to see how cartography is really done. 4 | \section{Colouring Features} 5 | \section{Line Styles} 6 | \section{Fonts} 7 | -------------------------------------------------------------------------------- /data/coast_ln_polyline.avl: -------------------------------------------------------------------------------- 1 | /3.2 2 | (ODB.1 3 | FirstRootClassName: "Legend" 4 | Roots: 2 5 | Version: 32 6 | ) 7 | 8 | (Legend.2 9 | SymType: 0x01 10 | LegType: 0x01 11 | ClassType: 0x03 12 | Symbols: 3 13 | Class: 6 14 | StdDevs: 1.00000000000000 15 | NullSym: 7 16 | NullValues: 9 17 | StatValues: 10 18 | Precision: -3 19 | ) 20 | 21 | (SymList.3 22 | Child: 4 23 | ) 24 | 25 | (BLnSym.4 26 | Color: 5 27 | Width: 1.00000000000000 28 | Pattern: 0.00000000000000 29 | Pattern: 0.00000000000000 30 | Pattern: 0.00000000000000 31 | Pattern: 0.00000000000000 32 | Pattern: 0.00000000000000 33 | Pattern: 0.00000000000000 34 | Pattern: 0.00000000000000 35 | Pattern: 0.00000000000000 36 | Pattern: 0.00000000000000 37 | Pattern: 0.00000000000000 38 | Pattern: 0.00000000000000 39 | Pattern: 0.00000000000000 40 | Pattern: 0.00000000000000 41 | Pattern: 0.00000000000000 42 | Pattern: 0.00000000000000 43 | Pattern: 0.00000000000000 44 | ) 45 | 46 | (TClr.5 47 | Red: 0xfe 48 | Green: 0xdb57 49 | Blue: 0xff00 50 | ) 51 | 52 | (LClass.6 53 | IsText: 1 54 | Precision: -3 55 | ) 56 | 57 | (BLnSym.7 58 | Color: 8 59 | Width: 0.10000000000000 60 | Pattern: 0.00000000000000 61 | Pattern: 0.00000000000000 62 | Pattern: 0.00000000000000 63 | Pattern: 0.00000000000000 64 | Pattern: 0.00000000000000 65 | Pattern: 0.00000000000000 66 | Pattern: 0.00000000000000 67 | Pattern: 0.00000000000000 68 | Pattern: 0.00000000000000 69 | Pattern: 0.00000000000000 70 | Pattern: 0.00000000000000 71 | Pattern: 0.00000000000000 72 | Pattern: 0.00000000000000 73 | Pattern: 0.00000000000000 74 | Pattern: 0.00000000000000 75 | Pattern: 0.00000000000000 76 | ) 77 | 78 | (TClr.8 79 | Name: "Transparent" 80 | ) 81 | 82 | (NameDict.9 83 | ) 84 | 85 | (NameDict.10 86 | ) 87 | 88 | -------------------------------------------------------------------------------- /data/coast_ln_polyline.dbf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/coast_ln_polyline.dbf -------------------------------------------------------------------------------- /data/coast_ln_polyline.prj: -------------------------------------------------------------------------------- 1 | PROJCS["British_National_Grid",GEOGCS["GCS_OSGB_1936",DATUM["D_OSGB_1936",SPHEROID["Airy_1830",6377563.396,299.3249646]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",400000.0],PARAMETER["False_Northing",-100000.0],PARAMETER["Central_Meridian",-2.0],PARAMETER["Scale_Factor",0.9996012717],PARAMETER["Latitude_Of_Origin",49.0],UNIT["Meter",1.0]] -------------------------------------------------------------------------------- /data/coast_ln_polyline.qix: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/coast_ln_polyline.qix -------------------------------------------------------------------------------- /data/coast_ln_polyline.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/coast_ln_polyline.shp -------------------------------------------------------------------------------- /data/coast_ln_polyline.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/coast_ln_polyline.shx -------------------------------------------------------------------------------- /data/coastline.sld: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | Meridian™ 2 7 | 8 | Coastline 9 | Meridian™ 2. Ordnance Survey. © Crown copyright and database rights 2013. 10 | 11 | 12 | 13 | 14 | 15 | Coastline - 1:23,607 To 1:94,482 16 | 17 | 18 | CODE 19 | 6200 20 | 21 | 22 | 23607 23 | 94482 24 | 25 | 26 | #5DC6DE 27 | 0.75 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /data/ne_10m_admin_0_countries.dbf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/ne_10m_admin_0_countries.dbf -------------------------------------------------------------------------------- /data/ne_10m_admin_0_countries.prj: -------------------------------------------------------------------------------- 1 | GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]] -------------------------------------------------------------------------------- /data/ne_10m_admin_0_countries.qix: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/ne_10m_admin_0_countries.qix -------------------------------------------------------------------------------- /data/ne_10m_admin_0_countries.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/ne_10m_admin_0_countries.shp -------------------------------------------------------------------------------- /data/ne_10m_admin_0_countries.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/ne_10m_admin_0_countries.shx -------------------------------------------------------------------------------- /data/states.dbf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/states.dbf -------------------------------------------------------------------------------- /data/states.prj: -------------------------------------------------------------------------------- 1 | GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]] 2 | -------------------------------------------------------------------------------- /data/states.qix: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/states.qix -------------------------------------------------------------------------------- /data/states.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/states.shp -------------------------------------------------------------------------------- /data/states.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/states.shx -------------------------------------------------------------------------------- /data/states_conic.dbf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/states_conic.dbf -------------------------------------------------------------------------------- /data/states_conic.fix: -------------------------------------------------------------------------------- 1 | 1  2 | 3 |   ! "!#"$#%$&%'&(')(*)+*,+-,.-/.0/10 -------------------------------------------------------------------------------- /data/states_conic.prj: -------------------------------------------------------------------------------- 1 | PROJCS["NAD83 / Conus Albers", GEOGCS["NAD83", DATUM["North American Datum 1983", SPHEROID["GRS 1980", 6378137.0, 298.257222101, AUTHORITY["EPSG","7019"]], TOWGS84[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], AUTHORITY["EPSG","6269"]], PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]], UNIT["degree", 0.017453292519943295], AXIS["Geodetic latitude", NORTH], AXIS["Geodetic longitude", EAST], AUTHORITY["EPSG","4269"]], PROJECTION["Albers_Conic_Equal_Area", AUTHORITY["EPSG","9822"]], PARAMETER["central_meridian", -96.0], PARAMETER["latitude_of_origin", 23.0], PARAMETER["standard_parallel_1", 29.5], PARAMETER["false_easting", 0.0], PARAMETER["false_northing", 0.0], PARAMETER["standard_parallel_2", 45.5], UNIT["m", 1.0], AXIS["Easting", EAST], AXIS["Northing", NORTH], AUTHORITY["EPSG","5070"]] -------------------------------------------------------------------------------- /data/states_conic.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/states_conic.shp -------------------------------------------------------------------------------- /data/states_conic.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/states_conic.shx -------------------------------------------------------------------------------- /data/world.200412.3x21600x10800.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/data/world.200412.3x21600x10800.jpg -------------------------------------------------------------------------------- /data/world.200412.3x21600x10800.jpw: -------------------------------------------------------------------------------- 1 | 0.0166666 2 | 0 3 | 0 4 | -0.0166666 5 | -180.0 6 | 90.0 7 | 8 | -------------------------------------------------------------------------------- /modules/distances/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | distances 5 | Distances 6 | measuring and geofences 7 | 8 | org.ianturton.cookbook 9 | modules 10 | 0.0.1-SNAPSHOT 11 | 12 | 13 | 14 | org.geotools 15 | gt-main 16 | ${geotools.version} 17 | 18 | 19 | org.geotools 20 | gt-render 21 | ${geotools.version} 22 | 23 | 24 | org.geotools 25 | gt-shapefile 26 | ${geotools.version} 27 | 28 | 29 | org.geotools 30 | gt-epsg-hsql 31 | ${geotools.version} 32 | 33 | 34 | -------------------------------------------------------------------------------- /modules/distances/src/main/java/org/ianturton/cookbook/distances/AutoProjection.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.distances; 2 | 3 | import javax.measure.Measure; 4 | import javax.measure.quantity.Length; 5 | import javax.measure.unit.SI; 6 | 7 | import org.geotools.geometry.jts.JTS; 8 | import org.geotools.geometry.jts.JTSFactoryFinder; 9 | import org.geotools.geometry.jts.WKTReader2; 10 | import org.geotools.referencing.CRS; 11 | import org.geotools.referencing.GeodeticCalculator; 12 | import org.geotools.referencing.crs.DefaultGeographicCRS; 13 | import org.opengis.geometry.MismatchedDimensionException; 14 | import org.opengis.referencing.FactoryException; 15 | import org.opengis.referencing.NoSuchAuthorityCodeException; 16 | import org.opengis.referencing.crs.CoordinateReferenceSystem; 17 | import org.opengis.referencing.operation.MathTransform; 18 | import org.opengis.referencing.operation.TransformException; 19 | 20 | import com.vividsolutions.jts.geom.Coordinate; 21 | import com.vividsolutions.jts.geom.Geometry; 22 | import com.vividsolutions.jts.geom.GeometryFactory; 23 | import com.vividsolutions.jts.geom.LineString; 24 | import com.vividsolutions.jts.geom.Point; 25 | import com.vividsolutions.jts.io.ParseException; 26 | 27 | public class AutoProjection { 28 | static GeometryFactory geometryFactory = JTSFactoryFinder 29 | .getGeometryFactory(null); 30 | static WKTReader2 reader = new WKTReader2(geometryFactory); 31 | 32 | public static void main(String[] args) throws ParseException, 33 | MismatchedDimensionException, NoSuchAuthorityCodeException, 34 | FactoryException, TransformException { 35 | Point p1 = getRandomPoint(); 36 | for (int i = 1; i < 50; i++) { 37 | 38 | double dx = i * Math.cos(Math.PI / 4); 39 | double dy = i * Math.sin(Math.PI / 4); 40 | Coordinate coordinate = new Coordinate(p1.getCoordinate().x + dx, 41 | p1.getCoordinate().y + dy); 42 | Point p2 = geometryFactory.createPoint(coordinate); 43 | // System.out.println(p2); 44 | System.out.print(Math.round(p1.distance(p2)) + " degrees \t"); 45 | AutoProjection me = new AutoProjection(); 46 | double distance = me.calculateDistance(p1, p2); 47 | double oDistance = me.calculateOrthoDistance(p1, p2); 48 | Measure dist = Measure.valueOf(distance, SI.METER); 49 | Measure oDist = Measure.valueOf(oDistance, SI.METER); 50 | double diff = Math.abs(distance - oDistance); 51 | Measure oDiff = Measure.valueOf(diff, SI.METER); 52 | System.out.println("Proj: " + dist.doubleValue(SI.KILOMETER) + " Km" 53 | + "\tOrtho: " + oDist.doubleValue(SI.KILOMETER) + " Km" + "\tDiff: " 54 | + oDiff.doubleValue(SI.KILOMETER) + " Km"); 55 | } 56 | } 57 | 58 | private double calculateDistance(Geometry g1, Geometry g2) 59 | throws NoSuchAuthorityCodeException, FactoryException, 60 | MismatchedDimensionException, TransformException { 61 | Point c1 = g1.getCentroid(); 62 | Point c2 = g2.getCentroid(); 63 | 64 | Coordinate[] coordinates = new Coordinate[2]; 65 | coordinates[0] = c1.getCoordinate(); 66 | coordinates[1] = c2.getCoordinate(); 67 | LineString line = geometryFactory.createLineString(coordinates); 68 | Point c = line.getCentroid(); 69 | double x = c.getCoordinate().x; 70 | double y = c.getCoordinate().y; 71 | /* 72 | * double x = (c1.getCoordinate().x - c2.getCoordinate().x) + 73 | * c1.getCoordinate().x; while (x > 180.0) { x -= 360.0; } while (x < 74 | * -180.0) { x += 360.0; } 75 | * 76 | * double y = (c1.getCoordinate().y - c2.getCoordinate().y) + 77 | * c1.getCoordinate().y; while (y > 90.0) { y -= 180.0; } while (x < -90.0) 78 | * { y += 180.0; } 79 | */ 80 | String code = "AUTO:42001," + y + "," + x; 81 | // System.out.println(code); 82 | CoordinateReferenceSystem auto = CRS.decode(code); 83 | // System.out.println(auto); 84 | MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, 85 | auto); 86 | Geometry g3 = JTS.transform(g1, transform); 87 | Geometry g4 = JTS.transform(g2, transform); 88 | return g3.distance(g4); 89 | } 90 | 91 | private double calculateOrthoDistance(Geometry g1, Geometry g2) { 92 | double distance = 0.0; 93 | Point c1 = g1.getCentroid(); 94 | Point c2 = g2.getCentroid(); 95 | GeodeticCalculator calc = new GeodeticCalculator(DefaultGeographicCRS.WGS84); 96 | calc.setStartingGeographicPoint(c1.getX(), c1.getY()); 97 | calc.setDestinationGeographicPoint(c2.getX(), c2.getY()); 98 | distance = calc.getOrthodromicDistance(); 99 | 100 | return distance; 101 | } 102 | 103 | private static Point getRandomPoint() { 104 | double lat = -90.0 + Math.random() * 180.0; 105 | double lon = -180.0 + Math.random() * 360.0; 106 | Point p = geometryFactory.createPoint(new Coordinate(lon, lat)); 107 | // System.out.println(p); 108 | return p; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /modules/distances/src/main/java/org/ianturton/cookbook/distances/OrthodromicDistance.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.distances; 2 | 3 | import javax.measure.Measure; 4 | import javax.measure.quantity.Length; 5 | import javax.measure.unit.NonSI; 6 | import javax.measure.unit.SI; 7 | 8 | import org.geotools.geometry.jts.JTS; 9 | import org.geotools.referencing.CRS; 10 | import org.geotools.referencing.CRS.AxisOrder; 11 | import org.geotools.referencing.crs.DefaultGeographicCRS; 12 | import org.opengis.referencing.FactoryException; 13 | import org.opengis.referencing.NoSuchAuthorityCodeException; 14 | import org.opengis.referencing.crs.CoordinateReferenceSystem; 15 | import org.opengis.referencing.operation.TransformException; 16 | 17 | import com.vividsolutions.jts.geom.Coordinate; 18 | import com.vividsolutions.jts.geom.GeometryFactory; 19 | import com.vividsolutions.jts.geom.Point; 20 | 21 | public class OrthodromicDistance { 22 | 23 | DefaultGeographicCRS default_crs = DefaultGeographicCRS.WGS84; 24 | 25 | /** 26 | * take two pairs of lat/long and return bearing and distance. 27 | * 28 | * @param args 29 | * @throws FactoryException 30 | * @throws NoSuchAuthorityCodeException 31 | */ 32 | public static void main(String[] args) 33 | throws NoSuchAuthorityCodeException, FactoryException { 34 | CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84; 35 | if (args.length < 4) { 36 | System.err 37 | .println("Need 4 numbers lat_1 lon_1 lat_2 lon_2 [epsgcode]"); 38 | return; 39 | } 40 | if (args.length > 4) { 41 | crs = CRS.decode(args[4]); 42 | } 43 | GeometryFactory geomFactory = new GeometryFactory(); 44 | Point[] points = new Point[2]; 45 | for (int i = 0, k = 0; i < 2; i++, k += 2) { 46 | double x = Double.valueOf(args[k]); 47 | double y = Double.valueOf(args[k + 1]); 48 | if (CRS.getAxisOrder(crs) 49 | .equals(AxisOrder.NORTH_EAST)) { 50 | points[i] = geomFactory.createPoint(new Coordinate( 51 | x, y)); 52 | } else { 53 | points[i] = geomFactory.createPoint(new Coordinate( 54 | y, x)); 55 | } 56 | 57 | } 58 | 59 | OrthodromicDistance d = new OrthodromicDistance(); 60 | d.calculateDistance(crs, points); 61 | } 62 | 63 | private void calculateDistance( 64 | CoordinateReferenceSystem crs, Point[] points) { 65 | if (crs == null) { 66 | crs = default_crs; 67 | } 68 | double distance = 0.0; 69 | try { 70 | distance = JTS.orthodromicDistance( 71 | points[0].getCoordinate(), 72 | points[1].getCoordinate(), crs); 73 | } catch (TransformException e) { 74 | // TODO Auto-generated catch block 75 | e.printStackTrace(); 76 | } 77 | 78 | Measure dist = Measure.valueOf( 79 | distance, SI.METER); 80 | System.out.println(dist.doubleValue(SI.KILOMETER) 81 | + " Km"); 82 | System.out.println(dist.doubleValue(NonSI.MILE) 83 | + " miles"); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /modules/distances/src/main/java/org/ianturton/cookbook/distances/OrthodromicDistance2.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.distances; 2 | 3 | import javax.measure.Measure; 4 | import javax.measure.quantity.Length; 5 | import javax.measure.unit.NonSI; 6 | import javax.measure.unit.SI; 7 | 8 | import org.geotools.referencing.CRS; 9 | import org.geotools.referencing.CRS.AxisOrder; 10 | import org.geotools.referencing.GeodeticCalculator; 11 | import org.geotools.referencing.crs.DefaultGeographicCRS; 12 | 13 | import com.vividsolutions.jts.geom.Coordinate; 14 | import com.vividsolutions.jts.geom.GeometryFactory; 15 | import com.vividsolutions.jts.geom.Point; 16 | 17 | public class OrthodromicDistance2 { 18 | /** 19 | * take two pairs of lat/long and return bearing and distance. 20 | * 21 | * @param args 22 | */ 23 | public static void main(String[] args) { 24 | DefaultGeographicCRS crs = DefaultGeographicCRS.WGS84; 25 | if (args.length != 4) { 26 | System.err.println("Need 4 numbers lat_1 lon_1 lat_2 lon_2"); 27 | return; 28 | } 29 | GeometryFactory geomFactory = new GeometryFactory(); 30 | Point[] points = new Point[2]; 31 | for (int i = 0, k = 0; i < 2; i++, k += 2) { 32 | double x = Double.valueOf(args[k]); 33 | double y = Double.valueOf(args[k + 1]); 34 | if (CRS.getAxisOrder(crs).equals(AxisOrder.NORTH_EAST)) { 35 | System.out.println("working with a lat/lon crs"); 36 | points[i] = geomFactory.createPoint(new Coordinate(x, y)); 37 | } else { 38 | System.out.println("working with a lon/lat crs"); 39 | points[i] = geomFactory.createPoint(new Coordinate(y, x)); 40 | } 41 | 42 | } 43 | 44 | 45 | double distance = 0.0; 46 | 47 | GeodeticCalculator calc = new GeodeticCalculator(crs); 48 | calc.setStartingGeographicPoint(points[0].getX(), points[0].getY()); 49 | calc.setDestinationGeographicPoint(points[1].getX(), points[1].getY()); 50 | distance = calc.getOrthodromicDistance(); 51 | double bearing = calc.getAzimuth(); 52 | 53 | Measure dist = Measure.valueOf(distance, SI.METER); 54 | System.out.println(dist.doubleValue(SI.KILOMETER) + " Km"); 55 | System.out.println(dist.doubleValue(NonSI.MILE) + " miles"); 56 | System.out.println("Bearing " + bearing + " degrees"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /modules/filters/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | org.ianturton.cookbook 6 | modules 7 | 0.0.1-SNAPSHOT 8 | 9 | filters 10 | filters 11 | working with featurecollections 12 | 13 | 14 | org.geotools 15 | gt-main 16 | ${geotools.version} 17 | 18 | 19 | org.geotools 20 | gt-cql 21 | ${geotools.version} 22 | 23 | 24 | org.geotools 25 | gt-api 26 | ${geotools.version} 27 | 28 | 29 | org.geotools 30 | gt-geotiff 31 | ${geotools.version} 32 | 33 | 34 | org.geotools 35 | gt-image 36 | ${geotools.version} 37 | 38 | 39 | org.geotools 40 | gt-wms 41 | ${geotools.version} 42 | 43 | 44 | org.geotools 45 | gt-render 46 | ${geotools.version} 47 | 48 | 49 | org.geotools 50 | gt-shapefile 51 | ${geotools.version} 52 | 53 | 54 | org.geotools 55 | gt-epsg-hsql 56 | ${geotools.version} 57 | 58 | 59 | 60 | org.geotools 61 | gt-swing 62 | ${geotools.version} 63 | 64 | 65 | org.geotools 66 | gt-grid 67 | ${geotools.version} 68 | 69 | 70 | org.geotools 71 | gt-arcgrid 72 | ${geotools.version} 73 | 74 | 75 | org.geotools 76 | gt-imageio-ext-gdal 77 | ${geotools.version} 78 | 79 | 80 | org.geotools 81 | gt-coverage 82 | ${geotools.version} 83 | 84 | 85 | commons-io 86 | commons-io 87 | 2.4 88 | 89 | 90 | 91 | net.sourceforge.javacsv 92 | javacsv 93 | 2.0 94 | 95 | 96 | com.sun.xml.bind 97 | jaxb-impl 98 | 2.1.13 99 | 100 | 101 | javax.media 102 | jai_core 103 | 1.1.3 104 | 105 | 107 | 108 | 109 | junit 110 | junit 111 | 4.11 112 | test 113 | 114 | 115 | org.apache.xmlgraphics 116 | batik-svggen 117 | 1.7 118 | 119 | 120 | org.apache.xmlgraphics 121 | batik-awt-util 122 | 1.7 123 | 124 | 125 | -------------------------------------------------------------------------------- /modules/filters/src/main/java/org/ianturton/cookbook/filters/PointInPolygon.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.filters; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | import org.geotools.data.FileDataStore; 7 | import org.geotools.data.FileDataStoreFinder; 8 | import org.geotools.data.simple.SimpleFeatureCollection; 9 | import org.geotools.data.simple.SimpleFeatureSource; 10 | import org.geotools.factory.CommonFactoryFinder; 11 | import org.geotools.factory.GeoTools; 12 | import org.geotools.geometry.jts.ReferencedEnvelope; 13 | import org.geotools.swing.data.JFileDataStoreChooser; 14 | import org.opengis.filter.Filter; 15 | import org.opengis.filter.FilterFactory2; 16 | import org.opengis.filter.expression.Expression; 17 | 18 | import com.vividsolutions.jts.geom.Coordinate; 19 | import com.vividsolutions.jts.geom.GeometryFactory; 20 | import com.vividsolutions.jts.geom.Point; 21 | 22 | public class PointInPolygon { 23 | FilterFactory2 filterFactory; 24 | private SimpleFeatureCollection features; 25 | private ReferencedEnvelope env; 26 | 27 | public static void main(String[] args) throws IOException { 28 | File file = null; 29 | if (args.length == 0) { 30 | // display a data store file chooser dialog for shapefiles 31 | file = JFileDataStoreChooser.showOpenFile("shp", null); 32 | if (file == null) { 33 | return; 34 | } 35 | } else { 36 | file = new File(args[0]); 37 | if (!file.exists()) { 38 | System.err.println(file + " doesn't exist"); 39 | return; 40 | } 41 | } 42 | PointInPolygon tester = new PointInPolygon(); 43 | FileDataStore store = FileDataStoreFinder.getDataStore(file); 44 | SimpleFeatureSource featureSource = store.getFeatureSource(); 45 | tester.setFeatures(featureSource.getFeatures()); 46 | GeometryFactory fac = new GeometryFactory(); 47 | for (int i = 0; i < 1000; i++) { 48 | 49 | double lat = (Math.random() * 180.0) - 90.0; 50 | double lon = (Math.random() * 360.0) - 180.0; 51 | Point p = fac.createPoint(new Coordinate(lat, lon)); 52 | boolean flag = tester.isInShape(p); 53 | if (flag) { 54 | System.out.println(p + " is in States "); 55 | } 56 | } 57 | } 58 | 59 | public PointInPolygon() { 60 | 61 | filterFactory = CommonFactoryFinder.getFilterFactory2(GeoTools 62 | .getDefaultHints()); 63 | } 64 | 65 | private boolean isInShape(Point p) { 66 | if (!env.contains(p.getCoordinate())) { 67 | return false; 68 | } 69 | Expression propertyName = filterFactory.property(features.getSchema() 70 | .getGeometryDescriptor().getName()); 71 | Filter filter = filterFactory.contains(propertyName, 72 | filterFactory.literal(p)); 73 | SimpleFeatureCollection sub = features.subCollection(filter); 74 | if (sub.size() > 0) { 75 | return true; 76 | } 77 | return false; 78 | } 79 | 80 | private void setFeatures(SimpleFeatureCollection features) { 81 | this.features = features; 82 | env = features.getBounds(); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /modules/filters/src/main/java/org/ianturton/cookbook/filters/QueryGrid.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.filters; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | import javax.measure.unit.Unit; 7 | import javax.media.jai.Histogram; 8 | 9 | import org.geotools.coverage.grid.GridCoverage2D; 10 | import org.geotools.coverage.grid.GridGeometry2D; 11 | import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader; 12 | import org.geotools.coverage.grid.io.AbstractGridFormat; 13 | import org.geotools.coverage.grid.io.GridFormatFinder; 14 | import org.geotools.coverage.processing.OperationJAI; 15 | import org.geotools.coverageio.gdal.aig.AIGReader; 16 | import org.geotools.data.DataSourceException; 17 | import org.opengis.coverage.grid.GridEnvelope; 18 | import org.opengis.geometry.Envelope; 19 | import org.opengis.parameter.ParameterValueGroup; 20 | 21 | /** 22 | * find all the cells in a grid coverage that are a set value. based on 23 | * http://stackoverflow 24 | * .com/questions/27761590/geotools-total-area-where-gridcoverage-has-value-x 25 | * 26 | * @author ian.turton 27 | * 28 | */ 29 | public class QueryGrid { 30 | 31 | public static void main(String[] args) { 32 | // load a file 33 | 34 | // File raster = new File("../../data/TQ19.asc"); 35 | File raster = new File("../../data/nzdem/nzdem500/hdr.adf"); 36 | 37 | AbstractGridFormat format = GridFormatFinder.findFormat(raster); 38 | AbstractGridCoverage2DReader reader = null; 39 | try { 40 | reader = format.getReader(raster); 41 | } catch (Exception e) { 42 | System.err.println("Failed to find a reader for " + raster); 43 | e.printStackTrace(); 44 | // return; 45 | } 46 | 47 | try { 48 | reader = new AIGReader(raster); 49 | } catch (DataSourceException e) { 50 | e.printStackTrace(); 51 | } 52 | 53 | GridCoverage2D cov; 54 | try { 55 | cov = reader.read(null); 56 | } catch (IOException giveUp) { 57 | throw new RuntimeException(giveUp); 58 | } 59 | 60 | QueryGrid queryGrid = new QueryGrid(); 61 | queryGrid.selectCells(cov, 135); 62 | queryGrid.selectCells(cov, 0); 63 | queryGrid.selectCells(cov, 134); 64 | 65 | } 66 | 67 | private double selectCells(GridCoverage2D cov, int value) { 68 | GridGeometry2D geom = cov.getGridGeometry(); 69 | // cov.show(); 70 | final OperationJAI op = new OperationJAI("Histogram"); 71 | ParameterValueGroup params = op.getParameters(); 72 | GridCoverage2D coverage; 73 | params.parameter("Source").setValue(cov); 74 | coverage = (GridCoverage2D) op.doOperation(params, null); 75 | javax.media.jai.Histogram hist = (Histogram) coverage 76 | .getProperty("histogram"); 77 | 78 | int total = hist.getSubTotal(0, value, value); 79 | double area = calcAreaOfCell(geom); 80 | Unit unit = cov.getCoordinateReferenceSystem().getCoordinateSystem() 81 | .getAxis(0).getUnit(); 82 | System.out.println("which gives " + (area * total) + " " + unit 83 | + "^2 area with value " + value); 84 | return area * total; 85 | } 86 | 87 | private double calcAreaOfCell(GridGeometry2D geom) { 88 | GridEnvelope gridRange = geom.getGridRange(); 89 | int width = gridRange.getHigh(0) - gridRange.getLow(0) + 1; // allow for the 90 | int height = gridRange.getHigh(1) - gridRange.getLow(1) + 1;// 0th row/col 91 | Envelope envelope = geom.getEnvelope(); 92 | double dWidth = envelope.getMaximum(0) - envelope.getMinimum(0); 93 | double dHeight = envelope.getMaximum(1) - envelope.getMinimum(1); 94 | double cellWidth = dWidth / width; 95 | double cellHeight = dHeight / height; 96 | 97 | return cellWidth * cellHeight; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /modules/input/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | input 5 | 6 | 7 | org.geotools 8 | gt-main 9 | ${geotools.version} 10 | 11 | 12 | org.geotools 13 | gt-cql 14 | ${geotools.version} 15 | 16 | 17 | org.geotools 18 | gt-api 19 | ${geotools.version} 20 | 21 | 22 | org.geotools 23 | gt-geotiff 24 | ${geotools.version} 25 | 26 | 27 | org.geotools 28 | gt-image 29 | ${geotools.version} 30 | 31 | 32 | org.geotools 33 | gt-wms 34 | ${geotools.version} 35 | 36 | 37 | org.geotools 38 | gt-render 39 | ${geotools.version} 40 | 41 | 42 | org.geotools 43 | gt-shapefile 44 | ${geotools.version} 45 | 46 | 47 | org.geotools 48 | gt-epsg-hsql 49 | ${geotools.version} 50 | 51 | 52 | 53 | org.geotools 54 | gt-swing 55 | ${geotools.version} 56 | 57 | 58 | org.geotools 59 | gt-grid 60 | ${geotools.version} 61 | 62 | 63 | 64 | commons-io 65 | commons-io 66 | 2.4 67 | 68 | 69 | 70 | net.sourceforge.javacsv 71 | javacsv 72 | 2.0 73 | 74 | 75 | com.sun.xml.bind 76 | jaxb-impl 77 | 2.1.13 78 | 79 | 80 | javax.media 81 | jai_core 82 | 1.1.3 83 | 84 | 85 | junit 86 | junit 87 | 4.11 88 | test 89 | 90 | 91 | org.apache.xmlgraphics 92 | batik-svggen 93 | 1.7 94 | 95 | 96 | org.apache.xmlgraphics 97 | batik-awt-util 98 | 1.7 99 | 100 | 101 | 102 | org.ianturton.cookbook 103 | modules 104 | 0.0.1-SNAPSHOT 105 | 106 | -------------------------------------------------------------------------------- /modules/output/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | output 5 | Generate Images 6 | 7 | org.ianturton.cookbook 8 | modules 9 | 0.0.1-SNAPSHOT 10 | 11 | 12 | 13 | 14 | 15 | 16 | org.geotools 17 | gt-main 18 | ${geotools.version} 19 | 20 | 21 | org.geotools 22 | gt-cql 23 | ${geotools.version} 24 | 25 | 26 | org.geotools 27 | gt-render 28 | ${geotools.version} 29 | 30 | 31 | org.geotools 32 | gt-shapefile 33 | ${geotools.version} 34 | 35 | 36 | org.geotools 37 | gt-epsg-hsql 38 | ${geotools.version} 39 | 40 | 41 | 42 | org.geotools 43 | gt-swing 44 | ${geotools.version} 45 | 46 | 47 | org.geotools 48 | gt-grid 49 | ${geotools.version} 50 | 51 | 52 | 53 | commons-io 54 | commons-io 55 | 2.4 56 | 57 | 58 | 59 | net.sourceforge.javacsv 60 | javacsv 61 | 2.0 62 | 63 | 64 | com.sun.xml.bind 65 | jaxb-impl 66 | 2.1.13 67 | 68 | 69 | javax.media 70 | jai_core 71 | 1.1.3 72 | 73 | 74 | junit 75 | junit 76 | 4.11 77 | test 78 | 79 | 80 | org.apache.xmlgraphics 81 | batik-svggen 82 | 1.7 83 | 84 | 85 | org.apache.xmlgraphics 86 | batik-awt-util 87 | 1.7 88 | 89 | 90 | 91 | org.ianturton.cookbook 92 | 0.0.1-SNAPSHOT 93 | -------------------------------------------------------------------------------- /modules/output/src/main/java/org/ianturton/cookbook/output/ExportGeometries.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.output; 2 | 3 | import com.vividsolutions.jts.geom.Coordinate; 4 | import com.vividsolutions.jts.geom.Geometry; 5 | import com.vividsolutions.jts.geom.GeometryFactory; 6 | import com.vividsolutions.jts.geom.LineString; 7 | import com.vividsolutions.jts.geom.MultiPolygon; 8 | import com.vividsolutions.jts.geom.Point; 9 | import com.vividsolutions.jts.geom.Polygon; 10 | 11 | public class ExportGeometries { 12 | 13 | public static void main(String[] args) { 14 | GeometryFactory fac = new GeometryFactory(); 15 | Point p = fac.createPoint(new Coordinate(10.1, 22.2)); 16 | System.out.println(getWKT(p)); 17 | // System.out.println(getCoordinates(p)); 18 | Coordinate[] coordinates = { new Coordinate(1, 1), new Coordinate(2, 3), 19 | new Coordinate(4.4, 5.2) }; 20 | LineString line = fac.createLineString(coordinates); 21 | System.out.println(getWKT(line)); 22 | // System.out.println(getCoordinates(line)); 23 | Coordinate[] pcoordinates = { new Coordinate(1, 1), new Coordinate(2, 3), 24 | new Coordinate(4.4, 5.2), new Coordinate(1, 1) }; 25 | Polygon poly = fac.createPolygon(pcoordinates); 26 | System.out.println(getWKT(poly)); 27 | // System.out.println(getCoordinates(poly)); 28 | Coordinate[] pcoordinates2 = { new Coordinate(10, 10), 29 | new Coordinate(20, 30), new Coordinate(40.4, 50.2), 30 | new Coordinate(10, 10) }; 31 | Polygon poly2 = fac.createPolygon(pcoordinates2); 32 | MultiPolygon multiPoly = fac 33 | .createMultiPolygon(new Polygon[] { poly, poly2 }); 34 | System.out.println(getWKT(multiPoly)); 35 | // System.out.println(getCoordinates(multiPoly)); 36 | } 37 | 38 | static String getWKT(Geometry geom) { 39 | return geom.toText(); 40 | } 41 | 42 | static String getCoordinates(Geometry geom) { 43 | StringBuilder builder = new StringBuilder(); 44 | if (geom.getNumGeometries() > 1) { 45 | for (int i = 0; i < geom.getNumGeometries(); i++) { 46 | builder.append(getCoordinates(geom.getGeometryN(i))); 47 | builder.append("\n"); 48 | } 49 | } else { 50 | 51 | Coordinate[] coords = geom.getCoordinates(); 52 | boolean first = true; 53 | for (Coordinate coord : coords) { 54 | if (!first) { 55 | builder.append(','); 56 | } 57 | first = false; 58 | builder.append(getCoord(coord)); 59 | 60 | } 61 | } 62 | return builder.toString(); 63 | } 64 | 65 | private static String getCoord(Coordinate coord) { 66 | StringBuilder builder = new StringBuilder(); 67 | builder.append(coord.x).append(",").append(coord.y); 68 | return builder.toString(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /modules/output/src/main/java/org/ianturton/cookbook/output/SaveMapAsImage.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.output; 2 | 3 | import java.awt.event.ActionEvent; 4 | import java.awt.image.RenderedImage; 5 | import java.io.File; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | 9 | import javax.imageio.ImageIO; 10 | import javax.imageio.stream.ImageOutputStream; 11 | import javax.swing.AbstractAction; 12 | import javax.swing.JOptionPane; 13 | import javax.swing.JToolBar; 14 | 15 | import org.geotools.data.FileDataStore; 16 | import org.geotools.data.FileDataStoreFinder; 17 | import org.geotools.data.simple.SimpleFeatureSource; 18 | import org.geotools.map.FeatureLayer; 19 | import org.geotools.map.Layer; 20 | import org.geotools.map.MapContent; 21 | import org.geotools.styling.SLD; 22 | import org.geotools.styling.Style; 23 | import org.geotools.swing.JMapFrame; 24 | import org.geotools.swing.JMapPane; 25 | import org.geotools.swing.data.JFileDataStoreChooser; 26 | 27 | public class SaveMapAsImage { 28 | 29 | private JMapFrame frame; 30 | private MapContent mapContent; 31 | 32 | public static void main(String[] args) throws IOException { 33 | File file = null; 34 | if (args.length == 0) { 35 | // display a data store file chooser dialog for shapefiles 36 | file = JFileDataStoreChooser.showOpenFile("shp", null); 37 | if (file == null) { 38 | return; 39 | } 40 | } else { 41 | file = new File(args[0]); 42 | if (!file.exists()) { 43 | System.err.println(file + " doesn't exist"); 44 | return; 45 | } 46 | } 47 | new SaveMapAsImage(file); 48 | } 49 | 50 | public SaveMapAsImage(File file) throws IOException { 51 | 52 | FileDataStore store = FileDataStoreFinder.getDataStore(file); 53 | SimpleFeatureSource featureSource = store.getFeatureSource(); 54 | 55 | // Create a map content and add our shapefile to it 56 | mapContent = new MapContent(); 57 | mapContent.setTitle("GeoTools Mapping"); 58 | Style style = SLD.createSimpleStyle(featureSource.getSchema()); 59 | Layer layer = new FeatureLayer(featureSource, style); 60 | mapContent.addLayer(layer); 61 | frame = new JMapFrame(mapContent); 62 | frame.enableStatusBar(true); 63 | frame.enableToolBar(true); 64 | JToolBar toolBar = frame.getToolBar(); 65 | toolBar.addSeparator(); 66 | SaveAction save = new SaveAction("Save"); 67 | toolBar.add(save); 68 | frame.initComponents(); 69 | frame.setSize(1000, 500); 70 | frame.setVisible(true); 71 | } 72 | 73 | public SaveMapAsImage() { 74 | // TODO Auto-generated constructor stub 75 | } 76 | 77 | public void drawMapToImage(File outputFile) { 78 | this.drawMapToImage(outputFile, "image/png"); 79 | } 80 | 81 | public void drawMapToImage(File outputFile, String outputType) { 82 | JMapPane mapPane = frame.getMapPane(); 83 | this.drawMapToImage(outputFile, outputType, mapPane); 84 | } 85 | 86 | public void drawMapToImage(File outputFile, String outputType, 87 | JMapPane mapPane) { 88 | ImageOutputStream outputImageFile = null; 89 | FileOutputStream fileOutputStream = null; 90 | try { 91 | fileOutputStream = new FileOutputStream(outputFile); 92 | outputImageFile = ImageIO.createImageOutputStream(fileOutputStream); 93 | RenderedImage bufferedImage = mapPane.getBaseImage(); 94 | ImageIO.write(bufferedImage, outputType, outputImageFile); 95 | } catch (IOException ex) { 96 | ex.printStackTrace(); 97 | } finally { 98 | try { 99 | if (outputImageFile != null) { 100 | outputImageFile.flush(); 101 | outputImageFile.close(); 102 | fileOutputStream.flush(); 103 | fileOutputStream.close(); 104 | } 105 | } catch (IOException e) {// don't care now 106 | } 107 | } 108 | } 109 | 110 | private class SaveAction extends AbstractAction { 111 | /** 112 | * Private SaveAction 113 | */ 114 | private static final long serialVersionUID = 3071568727121984649L; 115 | 116 | public SaveAction(String text) { 117 | super(text); 118 | } 119 | 120 | @Override 121 | public void actionPerformed(ActionEvent arg0) { 122 | String[] writers = ImageIO.getWriterFormatNames(); 123 | 124 | String format = (String) JOptionPane.showInputDialog(frame, 125 | "Choose output format:", "Customized Dialog", 126 | JOptionPane.PLAIN_MESSAGE, null, writers, "png"); 127 | drawMapToImage(new File("ian." + format), format); 128 | 129 | } 130 | 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /modules/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | org.ianturton.cookbook 5 | modules 6 | 0.0.1-SNAPSHOT 7 | modules 8 | 9 | org.ianturton 10 | cookbook 11 | 1.0 12 | 13 | 14 | 15 | 16 | 83 | 84 | pom 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-source-plugin 90 | 2.4 91 | 92 | 93 | attach-sources 94 | package 95 | 96 | jar-no-fork 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | quickstart 105 | input 106 | output 107 | filters 108 | distances 109 | projections 110 | styling 111 | conversion 112 | 113 | -------------------------------------------------------------------------------- /modules/projections/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | projections 4 | 5 | org.ianturton.cookbook 6 | modules 7 | 0.0.1-SNAPSHOT 8 | 9 | org.ianturton.cookbook 10 | 1.0-SNAPSHOT 11 | 12 | 13 | org.geotools 14 | gt-main 15 | ${geotools.version} 16 | 17 | 18 | org.geotools 19 | gt-render 20 | ${geotools.version} 21 | 22 | 23 | org.geotools 24 | gt-shapefile 25 | ${geotools.version} 26 | 27 | 28 | org.geotools 29 | gt-epsg-hsql 30 | ${geotools.version} 31 | 32 | 33 | org.geotools 34 | gt-grid 35 | ${geotools.version} 36 | 37 | 38 | org.geotools 39 | gt-swing 40 | ${geotools.version} 41 | 42 | 43 | -------------------------------------------------------------------------------- /modules/projections/src/main/java/org/ianturton/cookbook/projections/QueryEPSG.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.projections; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Set; 5 | 6 | import org.geotools.referencing.CRS; 7 | import org.opengis.referencing.FactoryException; 8 | import org.opengis.referencing.NoSuchAuthorityCodeException; 9 | import org.opengis.referencing.crs.CRSAuthorityFactory; 10 | import org.opengis.referencing.crs.CoordinateReferenceSystem; 11 | 12 | public class QueryEPSG { 13 | 14 | public static void main(String[] args) { 15 | QueryEPSG q = new QueryEPSG(); 16 | /* 17 | * ArrayList list = q.listDb(); // Collections.sort(list); for 18 | * (String desc : list) { System.out.println(desc); } 19 | */ 20 | /* 21 | * ArrayList crss = q.listCRS(); for 22 | * (CoordinateReferenceSystem crs : crss) { ReferenceIdentifier name = 23 | * crs.getName(); if (name != null) { Citation authority = 24 | * name.getAuthority(); if (authority != null) { 25 | * System.out.print(authority.getTitle() + " "); } 26 | * System.out.println(name.getCode() + " (" + name.getCodeSpace() + ")"); } 27 | * } 28 | */ 29 | ArrayList crss = q.selectCRS("GB"); 30 | for (CoordinateReferenceSystem crs : crss) { 31 | System.out.println(crs.toWKT()); 32 | System.out 33 | .println("----------------------------------------------------------------------------"); 34 | } 35 | } 36 | 37 | /** 38 | * search the CRS database and return any which include the string provided. 39 | * 40 | * @param value 41 | * - a string to search for. 42 | * @return an ArrayList of CRS that match (may be empty, but not null). 43 | */ 44 | private ArrayList selectCRS(String value) { 45 | String lValue = value.toLowerCase(); 46 | ArrayList ret = new ArrayList(); 47 | ArrayList possibles = listCRS(); 48 | CRSAuthorityFactory factory = CRS.getAuthorityFactory(false); 49 | 50 | for (CoordinateReferenceSystem crs : possibles) { 51 | if (crs.getName().getCode().toLowerCase().contains(lValue)) { 52 | ret.add(crs); 53 | } else if (crs.getName().getCodeSpace() != null 54 | && crs.getName().getCodeSpace().toLowerCase().contains(lValue)) { 55 | ret.add(crs); 56 | } else if (crs.getRemarks() != null 57 | && crs.getRemarks().toString().contains(lValue)) { 58 | ret.add(crs); 59 | } else if (crs.getCoordinateSystem().getRemarks() != null 60 | && crs.getCoordinateSystem().getRemarks().toString().toLowerCase() 61 | .contains(lValue)) { 62 | ret.add(crs); 63 | } 64 | 65 | } 66 | return ret; 67 | } 68 | 69 | /** 70 | * query the list of authorities and select CRS that are supported. 71 | * 72 | * @return a list of CRS. 73 | */ 74 | private ArrayList listCRS() { 75 | 76 | ArrayList ret = new ArrayList(); 77 | Set authorities = CRS.getSupportedAuthorities(false); 78 | for (String authority : authorities) { 79 | System.out.println("Looking up " + authority); 80 | Set codes = CRS.getSupportedCodes(authority); 81 | for (String code : codes) { 82 | try { 83 | if (!code.contains(":")) { 84 | code = authority + ":" + code; 85 | } 86 | ret.add(CRS.decode(code)); 87 | } catch (NoSuchAuthorityCodeException e) { 88 | // TODO Auto-generated catch block 89 | // e.printStackTrace(); 90 | } catch (FactoryException e) { 91 | // TODO Auto-generated catch block 92 | // e.printStackTrace(); 93 | } 94 | } 95 | } 96 | return ret; 97 | } 98 | 99 | /** 100 | * ask the Authority Factory to provide a list of CRS codes and Descriptions. 101 | * 102 | * @return a list of strings, code\tdescription. 103 | */ 104 | private ArrayList listDb() { 105 | ArrayList ret = new ArrayList(); 106 | CRSAuthorityFactory authFac = CRS.getAuthorityFactory(false); 107 | try { 108 | 109 | Set list = authFac 110 | .getAuthorityCodes(CoordinateReferenceSystem.class); 111 | 112 | for (String code : list) { 113 | ret.add(code + "\t" + authFac.getDescriptionText(code)); 114 | } 115 | } catch (FactoryException e) { 116 | // TODO Auto-generated catch block 117 | e.printStackTrace(); 118 | } 119 | return ret; 120 | 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /modules/quickstart/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | quickstart 5 | Getting Started 6 | 7 | org.ianturton.cookbook 8 | 0.0.1-SNAPSHOT 9 | modules 10 | 11 | 12 | 13 | 14 | org.codehaus.mojo 15 | exec-maven-plugin 16 | 1.2.1 17 | 18 | org.geotools.tutorial.quickstart.Quickstart 19 | ../../data/ne_10m_admin_0_countries.shp 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | org.geotools 30 | gt-main 31 | ${geotools.version} 32 | 33 | 34 | org.geotools 35 | gt-render 36 | ${geotools.version} 37 | 38 | 39 | org.geotools 40 | gt-shapefile 41 | ${geotools.version} 42 | 43 | 44 | org.geotools 45 | gt-geotiff 46 | ${geotools.version} 47 | 48 | 49 | org.geotools 50 | gt-epsg-hsql 51 | ${geotools.version} 52 | 53 | 54 | org.geotools 55 | gt-swing 56 | ${geotools.version} 57 | 58 | 59 | javax.media 60 | jai_core 61 | 1.1.3 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/java/org/geotools/tutorial/quickstart/Quickstart.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.quickstart; 2 | 3 | import java.io.File; 4 | 5 | import org.geotools.data.FileDataStore; 6 | import org.geotools.data.FileDataStoreFinder; 7 | import org.geotools.data.simple.SimpleFeatureSource; 8 | import org.geotools.map.FeatureLayer; 9 | import org.geotools.map.Layer; 10 | import org.geotools.map.MapContent; 11 | import org.geotools.styling.SLD; 12 | import org.geotools.styling.Style; 13 | import org.geotools.swing.JMapFrame; 14 | import org.geotools.swing.data.JFileDataStoreChooser; 15 | 16 | /** 17 | * Prompts the user for a shapefile and displays the contents on the screen in a 18 | * map frame. 19 | *

20 | * This is the GeoTools Quickstart application used in documentationa and 21 | * tutorials. 22 | */ 23 | public class Quickstart { 24 | 25 | /** 26 | * GeoTools Quickstart demo application. Prompts the user for a shapefile 27 | * and displays its contents on the screen in a map frame 28 | */ 29 | public static void main(String[] args) throws Exception { 30 | File file = null; 31 | if (args.length >= 1) { 32 | file = new File(args[0]); 33 | } 34 | if (file == null) { 35 | // display a data store file chooser dialog for shapefiles 36 | file = JFileDataStoreChooser.showOpenFile("shp", null); 37 | if (file == null) { 38 | return; 39 | } 40 | } 41 | FileDataStore store = FileDataStoreFinder.getDataStore(file); 42 | SimpleFeatureSource featureSource = store.getFeatureSource(); 43 | 44 | // Create a map content and add our shapefile to it 45 | MapContent map = new MapContent(); 46 | map.setTitle("Quickstart"); 47 | 48 | Style style = SLD.createSimpleStyle(featureSource.getSchema()); 49 | Layer layer = new FeatureLayer(featureSource, style); 50 | map.addLayer(layer); 51 | 52 | // Now display the map 53 | JMapFrame.showMap(map); 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/java/org/geotools/tutorial/quickstart/QuickstartCache.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.quickstart; 2 | 3 | import java.io.File; 4 | 5 | import org.geotools.data.CachingFeatureSource; 6 | import org.geotools.data.FileDataStore; 7 | import org.geotools.data.FileDataStoreFinder; 8 | import org.geotools.data.simple.SimpleFeatureSource; 9 | import org.geotools.map.FeatureLayer; 10 | import org.geotools.map.Layer; 11 | import org.geotools.map.MapContent; 12 | import org.geotools.styling.SLD; 13 | import org.geotools.styling.Style; 14 | import org.geotools.swing.JMapFrame; 15 | import org.geotools.swing.data.JFileDataStoreChooser; 16 | 17 | /** 18 | * Example used in Quickstart workbook showing how to use a CachingFeatureSource. 19 | *

20 | * This is the GeoTools Quickstart application used in documentationa and tutorials. * 21 | */ 22 | public class QuickstartCache { 23 | 24 | // docs start cache 25 | /** 26 | * This method demonstrates using a memory-based cache to speed up the display (e.g. when 27 | * zooming in and out). 28 | * 29 | * There is just one line extra compared to the main method, where we create an instance of 30 | * CachingFeatureStore. 31 | */ 32 | public static void main(String[] args) throws Exception { 33 | // display a data store file chooser dialog for shapefiles 34 | File file = JFileDataStoreChooser.showOpenFile("shp", null); 35 | if (file == null) { 36 | return; 37 | } 38 | 39 | FileDataStore store = FileDataStoreFinder.getDataStore(file); 40 | SimpleFeatureSource featureSource = store.getFeatureSource(); 41 | 42 | CachingFeatureSource cache = new CachingFeatureSource(featureSource); 43 | 44 | // Create a map content and add our shapefile to it 45 | MapContent map = new MapContent(); 46 | map.setTitle("Using cached features"); 47 | Style style = SLD.createSimpleStyle(featureSource.getSchema()); 48 | Layer layer = new FeatureLayer(cache, style); 49 | map.addLayer(layer); 50 | 51 | // Now display the map 52 | JMapFrame.showMap(map); 53 | } 54 | // docs end cache 55 | } 56 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/java/org/geotools/tutorial/quickstart/QuickstartNotes.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.quickstart; 2 | 3 | import java.io.File; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import org.geotools.data.DataStore; 8 | import org.geotools.data.DataStoreFinder; 9 | import org.geotools.data.simple.SimpleFeatureSource; 10 | import org.geotools.swing.data.JFileDataStoreChooser; 11 | 12 | /** 13 | * Additional code examples used by the quickstart tutorial; mostly for the things to try 14 | * section at the end. 15 | */ 16 | class QuickstartNotes { 17 | 18 | public void snipetDataStoreFinder() throws Exception { 19 | // start datastore 20 | File file = JFileDataStoreChooser.showOpenFile("shp", null); 21 | 22 | Map params = new HashMap(); 23 | params.put( "url", file.toURI().toURL() ); 24 | params.put( "create spatial index", false ); 25 | params.put( "memory mapped buffer", false ); 26 | params.put( "charset", "ISO-8859-1" ); 27 | 28 | DataStore store = DataStoreFinder.getDataStore( params ); 29 | SimpleFeatureSource featureSource = store.getFeatureSource( store.getTypeNames()[0] ); 30 | // end datastore 31 | } 32 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/api/DataStoreExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.api; 2 | 3 | import java.net.URI; 4 | import java.util.Set; 5 | 6 | import org.geotools.data.DataStore; 7 | import org.geotools.data.DataUtilities; 8 | import org.geotools.data.Query; 9 | import org.geotools.data.ServiceInfo; 10 | import org.geotools.data.simple.SimpleFeatureSource; 11 | import org.geotools.feature.NameImpl; 12 | import org.geotools.filter.text.cql2.CQL; 13 | import org.opengis.feature.simple.SimpleFeatureType; 14 | import org.opengis.feature.type.Name; 15 | 16 | 17 | public class DataStoreExamples { 18 | 19 | DataStore dataStore = null; 20 | SimpleFeatureSource featureSource = null; 21 | 22 | void exampleInfo() { 23 | // exampleInfo start 24 | ServiceInfo info = dataStore.getInfo(); 25 | 26 | // Human readable name and description 27 | String title = info.getTitle(); 28 | String text = info.getDescription(); 29 | 30 | // keywords (dublin core keywords like a web page) 31 | Set keywords = info.getKeywords(); 32 | 33 | // formal metadata 34 | URI publisher = info.getPublisher(); // authority publishing data 35 | URI schema = info.getSchema(); // used for data conforming to a standard 36 | URI source = info.getSource(); // location where information is published from 37 | 38 | // exampleInfo end 39 | } 40 | 41 | void exampleCreateSchema() throws Exception { 42 | // exampleCreateSchema start 43 | SimpleFeatureType schema = DataUtilities.createType("LINE", "centerline:LineString,name:\"\",id:0"); 44 | 45 | dataStore.createSchema( schema ); 46 | // exampleCreateSchema end 47 | 48 | } 49 | 50 | void exampleRemoveSchema() throws Exception { 51 | // exampleRemoveSchema start 52 | Name schemaName = new NameImpl("myTable"); 53 | dataStore.removeSchema(schemaName); 54 | // exampleRemoveSchema end 55 | 56 | } 57 | 58 | void exampleAllCount() throws Exception { 59 | // all start 60 | int count = featureSource.getCount( Query.ALL ); 61 | if( count == -1 ){ 62 | count = featureSource.getFeatures().size(); 63 | } 64 | // all end 65 | } 66 | 67 | void exampleQueryCount() throws Exception { 68 | // count start 69 | Query query = new Query( "typeName", CQL.toFilter("REGION = 3") ); 70 | int count = featureSource.getCount( query ); 71 | if( count == -1 ){ 72 | count = featureSource.getFeatures( query ).size(); 73 | } 74 | // count end 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/api/validation/ValidationExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.api.validation; 2 | 3 | import java.io.File; 4 | import java.util.HashMap; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | import java.util.Set; 8 | 9 | import org.geotools.data.memory.MemoryDataStore; 10 | import org.geotools.data.simple.SimpleFeatureCollection; 11 | import org.geotools.data.simple.SimpleFeatureSource; 12 | import org.geotools.feature.NameImpl; 13 | import org.geotools.validation.DefaultFeatureResults; 14 | import org.geotools.validation.ValidationProcessor; 15 | import org.geotools.validation.spatial.IsValidGeometryValidation; 16 | import org.opengis.feature.simple.SimpleFeatureType; 17 | import org.opengis.feature.type.Name; 18 | 19 | @SuppressWarnings("unused") 20 | public class ValidationExamples { 21 | 22 | private void validationExample() throws Exception{ 23 | SimpleFeatureCollection roadFeatures = null; 24 | SimpleFeatureCollection riverFeatures = null; 25 | 26 | // validationExample start 27 | MemoryDataStore store; 28 | store = new MemoryDataStore(); 29 | store.addFeatures( roadFeatures ); 30 | store.addFeatures( riverFeatures ); 31 | 32 | // 33 | // SETUP 34 | // 35 | ValidationProcessor processor = new ValidationProcessor(); 36 | 37 | // normally you load definition from file 38 | // Here we are doing it by hand 39 | IsValidGeometryValidation geom = new IsValidGeometryValidation(); 40 | geom.setName( "IsValidGeometry"); 41 | geom.setDescription("IsValid geomtry check"); 42 | geom.setTypeRef("*"); // works on any feature type 43 | processor.addValidation( geom ); 44 | 45 | // 46 | // TESTING 47 | // 48 | 49 | // Create a ValidationResults callback object to receive 50 | // any warnings or errors 51 | // 52 | // Normally you implement this as a callback to your application; 53 | // here we will use a default implementation here that adds results to a list 54 | DefaultFeatureResults results = new DefaultFeatureResults(); 55 | 56 | // test a featureCollection 57 | processor.runFeatureTests( "dataStoreId", roadFeatures, results); 58 | 59 | // and check the results 60 | System.out.println("Found "+ results.error.size() + " failires" ); 61 | // validationExample end 62 | } 63 | 64 | private void validationExample2() throws Exception { 65 | File pluginDirectory = null; 66 | File testSuiteDirectory = null; 67 | SimpleFeatureSource lakesFeatureSource = null; 68 | SimpleFeatureSource streamsFeatureSource = null; 69 | 70 | // validationExample2 start 71 | 72 | // set up a validation processor using two directories of 73 | // configuraiton files 74 | ValidationProcessor processor = new ValidationProcessor(); 75 | processor.load( pluginDirectory, testSuiteDirectory ); 76 | 77 | // normally you load definition from file 78 | // it will load all the files in the provided directories 79 | processor.load( pluginDirectory, testSuiteDirectory ); 80 | 81 | DefaultFeatureResults results = new DefaultFeatureResults(); 82 | 83 | // To run integrity tests (that compare several featureSources we need 84 | // to make a Map of FeatureSources. 85 | // the *key* is called the "typeRef" and will be used by test suites 86 | // to refer to look up a featureSource as needed 87 | Map map = new HashMap(); 88 | 89 | // register in map so validation processor can find it 90 | map.put( "LAKES:lakes", lakesFeatureSource ); 91 | map.put( "STREAMS:streams", streamsFeatureSource ); 92 | // optional shortlist of layers to check (these are usually the layers your 93 | // user modified) 94 | Set check = new HashSet(); 95 | check.add( new NameImpl("LAKES:lakes")); 96 | 97 | processor.runIntegrityTests( check, map, null, results); 98 | 99 | // and check the results 100 | System.out.println("Found "+ results.error.size() + " failires" ); 101 | // validationExample2 end 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/coverage/CoverageExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.coverage; 2 | 3 | import java.awt.image.BufferedImage; 4 | import java.awt.image.RenderedImage; 5 | import java.io.File; 6 | 7 | import org.geotools.coverage.grid.GridCoverage2D; 8 | import org.geotools.coverage.grid.GridCoverageFactory; 9 | import org.geotools.coverage.grid.io.AbstractGridFormat; 10 | import org.geotools.coverage.grid.io.GridCoverage2DReader; 11 | import org.geotools.coverage.grid.io.GridFormatFinder; 12 | import org.geotools.geometry.DirectPosition2D; 13 | import org.geotools.geometry.jts.ReferencedEnvelope; 14 | import org.opengis.geometry.DirectPosition; 15 | import org.opengis.geometry.Envelope; 16 | import org.opengis.referencing.crs.CoordinateReferenceSystem; 17 | 18 | /** 19 | * Coverage Examples used for sphinx documentation. 20 | * 21 | * @author Jody Garnett 22 | */ 23 | public class CoverageExamples { 24 | 25 | @SuppressWarnings("unused") 26 | void exampleGridFormat() throws Exception { 27 | 28 | // exampleGridFormat start 29 | File file = new File("test.tiff"); 30 | 31 | AbstractGridFormat format = GridFormatFinder.findFormat(file); 32 | GridCoverage2DReader reader = format.getReader(file); 33 | 34 | GridCoverage2D coverage = reader.read(null); 35 | // exampleGridFormat end 36 | } 37 | 38 | @SuppressWarnings("unused") 39 | void exampleGridCoverageFactory() throws Exception { 40 | 41 | ReferencedEnvelope referencedEnvelope = null; 42 | BufferedImage bufferedImage = null; 43 | // exampleGridCoverageFactory start 44 | GridCoverageFactory factory = new GridCoverageFactory(); 45 | GridCoverage2D coverage = factory.create("GridCoverage", bufferedImage, referencedEnvelope); 46 | // exampleGridCoverageFactory end 47 | } 48 | 49 | 50 | @SuppressWarnings("unused") 51 | void exampleGridCoverageUsing() throws Exception { 52 | File file = new File("test.tiff"); 53 | AbstractGridFormat format = GridFormatFinder.findFormat(file); 54 | GridCoverage2DReader reader = format.getReader(file); 55 | // exampleGridCoverageUsing start 56 | GridCoverage2D coverage = reader.read(null); 57 | 58 | CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem2D(); 59 | Envelope env = coverage.getEnvelope(); 60 | RenderedImage image = coverage.getRenderedImage(); 61 | // exampleGridCoverageUsing end 62 | } 63 | 64 | void exampleGridCoverageDirect() throws Exception { 65 | double x =0; 66 | double y = 0; 67 | CoordinateReferenceSystem crs = null; 68 | 69 | File file = new File("test.tiff"); 70 | AbstractGridFormat format = GridFormatFinder.findFormat(file); 71 | GridCoverage2DReader reader = format.getReader(file); 72 | // exampleGridCoverageDirect start 73 | GridCoverage2D coverage = reader.read(null); 74 | 75 | // direct access 76 | DirectPosition position = new DirectPosition2D( crs, x, y); 77 | 78 | double[] sample = (double[]) coverage.evaluate( position ); // assume double 79 | 80 | // resample with the same array 81 | sample = coverage.evaluate( position, sample ); 82 | // exampleGridCoverageDirect end 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/cql/DataExamples.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package org.geotools.cql; 5 | 6 | import java.io.IOException; 7 | import java.text.SimpleDateFormat; 8 | 9 | import org.apache.commons.io.FileUtils; 10 | import org.geotools.data.DataUtilities; 11 | import org.geotools.feature.simple.SimpleFeatureBuilder; 12 | import org.geotools.geometry.jts.JTSFactoryFinder; 13 | import org.opengis.feature.simple.SimpleFeature; 14 | import org.opengis.feature.simple.SimpleFeatureType; 15 | 16 | import com.vividsolutions.jts.geom.Coordinate; 17 | import com.vividsolutions.jts.geom.GeometryFactory; 18 | import com.vividsolutions.jts.geom.MultiPolygon; 19 | import com.vividsolutions.jts.geom.Point; 20 | import com.vividsolutions.jts.io.WKTReader; 21 | 22 | /** 23 | * This utility class provide the data required by the CQL/ECQL examples. 24 | * 25 | * @author Mauricio Pazos 26 | * 27 | */ 28 | final class DataExamples extends ECQLExamples { 29 | 30 | private static SimpleFeature COUNTRY = null; 31 | 32 | private static SimpleFeature CITY = null; 33 | 34 | private DataExamples() { 35 | // utility class 36 | } 37 | 38 | /** 39 | * Creates a feature that represent New York city 40 | * 41 | * @return a Feature 42 | * @throws Exception 43 | */ 44 | static public SimpleFeature getInstanceOfCity() throws Exception { 45 | 46 | if (CITY != null) { 47 | return CITY; 48 | } 49 | 50 | final SimpleFeatureType type = DataUtilities 51 | .createType("Location", "geometry:Point:srid=4326," + "cityName:String," 52 | + "over65YearsOld:Double," + "under18YearsOld:Double," 53 | + "population:Integer," + "lastEarthQuake:Date"); 54 | SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(type); 55 | 56 | GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); 57 | 58 | Point point = geometryFactory.createPoint(new Coordinate(-17.2053, 11.9517)); 59 | 60 | featureBuilder.add(point); 61 | featureBuilder.add("New York"); 62 | featureBuilder.add(22.6); 63 | featureBuilder.add(13.4); 64 | featureBuilder.add(19541453); 65 | 66 | SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); 67 | featureBuilder.add(dateFormatter.parse("1737-11-30T01:30:00Z")); 68 | 69 | CITY = featureBuilder.buildFeature(null); 70 | 71 | return CITY; 72 | } 73 | 74 | public static SimpleFeature getInstanceOfCountry() throws Exception { 75 | 76 | if (COUNTRY != null) { 77 | return COUNTRY; 78 | } 79 | final SimpleFeatureType type = DataUtilities.createType("Location", 80 | "geometry:Polygon:srid=4326," + "countryName:String," + "population:Integer," 81 | + "principalMineralResource:String"); 82 | SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(type); 83 | 84 | WKTReader reader = new WKTReader(); 85 | MultiPolygon geometry = (MultiPolygon) reader.read(usaGeometry()); 86 | 87 | featureBuilder.add(geometry); 88 | featureBuilder.add("USA"); 89 | featureBuilder.add(307006550); 90 | featureBuilder.add("oil"); 91 | 92 | COUNTRY = featureBuilder.buildFeature(null); 93 | 94 | return COUNTRY; 95 | } 96 | 97 | static private String usaGeometry() { 98 | try { 99 | return FileUtils.readFileToString( 100 | DataUtilities.urlToFile(DataExamples.class.getResource("usa-geometry.wkt")), 101 | "UTF-8"); 102 | } catch (IOException e) { 103 | throw new RuntimeException(e); 104 | } 105 | } 106 | 107 | /** 108 | * Show USA geometry can be loaded and used to make a SimpleFeature. 109 | */ 110 | public static void main(String[] args) { 111 | try { 112 | System.out.println(getInstanceOfCountry()); 113 | } catch (Exception e) { 114 | throw new RuntimeException(e); 115 | } 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/cql/Utility.java: -------------------------------------------------------------------------------- 1 | 2 | package org.geotools.cql; 3 | 4 | import org.opengis.filter.Filter; 5 | 6 | /** 7 | * This class maintains set of common functions used in the CQL and ECQL examples 8 | * 9 | * @author Mauricio Pazos 10 | * 11 | */ 12 | final class Utility { 13 | 14 | 15 | private Utility(){ 16 | // utility class 17 | } 18 | public static void prittyPrintFilter(Filter filter) { 19 | System.out.println("The filter result is:\n" + filter.toString()); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/data/property/PropertyDataStore.java: -------------------------------------------------------------------------------- 1 | package org.geotools.data.property; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.FilenameFilter; 7 | import java.io.IOException; 8 | 9 | import org.geotools.data.AbstractDataStore; 10 | import org.geotools.data.DataSourceException; 11 | import org.geotools.data.DataUtilities; 12 | import org.geotools.data.FeatureReader; 13 | import org.geotools.feature.SchemaException; 14 | import org.opengis.feature.simple.SimpleFeature; 15 | import org.opengis.feature.simple.SimpleFeatureType; 16 | 17 | public class PropertyDataStore extends AbstractDataStore { 18 | protected File directory; 19 | 20 | protected String namespaceURI; 21 | 22 | public PropertyDataStore(File dir) { 23 | this(dir, null); 24 | } 25 | 26 | public PropertyDataStore(File dir, String namespaceURI) { 27 | if (!dir.isDirectory()) { 28 | throw new IllegalArgumentException(dir + " is not a directory"); 29 | } 30 | if (namespaceURI == null) { 31 | namespaceURI = dir.getName(); 32 | } 33 | directory = dir; 34 | this.namespaceURI = namespaceURI; 35 | } 36 | 37 | // definition end 38 | 39 | // getTypeNames start 40 | /** 41 | * Gets the names of feature types available in this {@code DataStore}. 42 | * 43 | * @return array of type name's published by this datastore 44 | */ 45 | public String[] getTypeNames() { 46 | String list[] = directory.list(new FilenameFilter() { 47 | public boolean accept(File dir, String name) { 48 | return name.endsWith(".properties"); 49 | } 50 | }); 51 | for (int i = 0; i < list.length; i++) { 52 | list[i] = list[i].substring(0, list[i].lastIndexOf('.')); 53 | } 54 | return list; 55 | } 56 | 57 | // getTypeNames end 58 | 59 | // getSchema start 60 | /** 61 | * Creates a Schema (FeatureType) from the first line of the .properties 62 | * file 63 | * 64 | * @param typeName TypeName indicating the property file used 65 | */ 66 | public SimpleFeatureType getSchema(String typeName) throws IOException { 67 | String typeSpec = property(typeName, "_"); 68 | try { 69 | String namespace = directory.getName(); 70 | return DataUtilities.createType(namespace + "." + typeName, 71 | typeSpec); 72 | } catch (SchemaException e) { 73 | e.printStackTrace(); 74 | throw new DataSourceException(typeName + " schema not available", e); 75 | } 76 | } 77 | 78 | // getSchema end 79 | 80 | // property start 81 | /** 82 | * Opens the file given in typeName and reads through looking for a line 83 | * that begins with key and then "=". 84 | * 85 | * @param typeName indicates file to open 86 | * @param key indicates the line to read 87 | * @return the key's values (everything to the right of the '=' 88 | * @throws IOException 89 | */ 90 | private String property(String typeName, String key) throws IOException { 91 | File file = new File(directory, typeName + ".properties"); 92 | BufferedReader reader = new BufferedReader(new FileReader(file)); 93 | try { 94 | for (String line = reader.readLine(); line != null; line = reader 95 | .readLine()) { 96 | if (line.startsWith(key + "=")) { 97 | return line.substring(key.length() + 1); 98 | } 99 | } 100 | } finally { 101 | reader.close(); 102 | } 103 | return null; 104 | } 105 | 106 | // property end 107 | 108 | // getFeatureReader start 109 | /** 110 | * Implements access to the "raw" FeatureReader, this method is called 111 | * internally by AbstractDataStore. 112 | * 113 | * @param typeName TypeName indicating property file to read 114 | * @return FeatureReader providing access to contents of file 115 | */ 116 | protected FeatureReader getFeatureReader( 117 | String typeName) throws IOException { 118 | return new PropertyFeatureReader(directory, typeName); 119 | } 120 | // getFeatureReader end 121 | } 122 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/data/property/PropertyFeatureReader.java: -------------------------------------------------------------------------------- 1 | package org.geotools.data.property; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.NoSuchElementException; 6 | import java.util.logging.Logger; 7 | 8 | import org.geotools.data.FeatureReader; 9 | import org.geotools.feature.simple.SimpleFeatureBuilder; 10 | import org.geotools.util.logging.Logging; 11 | import org.opengis.feature.IllegalAttributeException; 12 | import org.opengis.feature.simple.SimpleFeature; 13 | import org.opengis.feature.simple.SimpleFeatureType; 14 | 15 | /** 16 | * FeatureReader access to the contents of a PropertyFile. 17 | * 18 | * @author Jody Garnett 19 | * @version 8.0.0 20 | * @since 2.0.0 21 | */ 22 | public class PropertyFeatureReader implements 23 | FeatureReader { 24 | private static final Logger LOGGER = Logging 25 | .getLogger("org.geotools.data.property"); 26 | 27 | PropertyAttributeReader reader; 28 | 29 | /** 30 | * Creates a new PropertyFeatureReader object. 31 | * 32 | * @param directory Directory containing property file 33 | * @param typeName TypeName indicating file to read 34 | * @throws IOException 35 | */ 36 | public PropertyFeatureReader(File directory, String typeName) 37 | throws IOException { 38 | File file = new File(directory, typeName + ".properties"); 39 | reader = new PropertyAttributeReader(file); 40 | } 41 | 42 | /** 43 | * Access to schema description. 44 | * 45 | * @return SimpleFeatureType describing attribtues 46 | */ 47 | public SimpleFeatureType getFeatureType() { 48 | return reader.type; 49 | } 50 | 51 | /** 52 | * Access the next feature (if available). 53 | * 54 | * @return SimpleFeature read from property file 55 | * @throws IOException 56 | * @throws IllegalAttributeException 57 | * @throws NoSuchElementException 58 | */ 59 | public SimpleFeature next() throws IOException, IllegalAttributeException, 60 | NoSuchElementException { 61 | reader.next(); 62 | 63 | SimpleFeatureType type = reader.type; 64 | String fid = reader.getFeatureID(); 65 | Object[] values = new Object[reader.getAttributeCount()]; 66 | 67 | for (int i = 0; i < reader.getAttributeCount(); i++) { 68 | try { 69 | values[i] = reader.read(i); 70 | } catch (RuntimeException e) { 71 | values[i] = null; 72 | } catch (IOException e) { 73 | throw e; 74 | } 75 | } 76 | return SimpleFeatureBuilder.build(type, values, fid); 77 | } 78 | 79 | /** 80 | * Check if additional contents are available. 81 | * 82 | * @return true if additional contents are available 83 | * @throws IOException 84 | */ 85 | public boolean hasNext() throws IOException { 86 | return reader.hasNext(); 87 | } 88 | 89 | /** 90 | * Close the FeatureReader when not in use. 91 | * 92 | * @throws IOException 93 | */ 94 | public void close() throws IOException { 95 | if (reader == null) { 96 | LOGGER.warning("Stream seems to be already closed."); 97 | } else { 98 | reader.close(); 99 | } 100 | reader = null; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/geometry/GeometryExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.geometry; 2 | 3 | import org.geotools.geometry.jts.Geometries; 4 | import org.geotools.geometry.jts.JTSFactoryFinder; 5 | 6 | import com.vividsolutions.jts.geom.Coordinate; 7 | import com.vividsolutions.jts.geom.Geometry; 8 | import com.vividsolutions.jts.geom.GeometryFactory; 9 | import com.vividsolutions.jts.geom.Point; 10 | import com.vividsolutions.jts.io.ParseException; 11 | import com.vividsolutions.jts.io.WKTReader; 12 | 13 | public class GeometryExamples { 14 | 15 | public void createPoint() { 16 | // createPoint start 17 | GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); 18 | 19 | Coordinate coord = new Coordinate(1, 1); 20 | Point point = geometryFactory.createPoint(coord); 21 | // createPoint end 22 | } 23 | 24 | public void createPointWKT() throws ParseException { 25 | // createPointWKT start 26 | GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); 27 | 28 | WKTReader reader = new WKTReader(geometryFactory); 29 | Point point = (Point) reader.read("POINT (1 1)"); 30 | // createPointWKT end 31 | } 32 | 33 | // geometries start 34 | public boolean hit(Point point, Geometry geometry) { 35 | final double MAX_DISTANCE = 0.001; 36 | 37 | switch (Geometries.get(geometry)) { 38 | case POINT: 39 | case MULTIPOINT: 40 | case LINESTRING: 41 | case MULTILINESTRING: 42 | // Test if p is within a threshold distance 43 | return geometry.isWithinDistance(point, MAX_DISTANCE); 44 | 45 | case POLYGON: 46 | case MULTIPOLYGON: 47 | // Test if the polygonal geometry contains p 48 | return geometry.contains(point); 49 | 50 | default: 51 | // For simplicity we just assume distance check will work for other 52 | // types (e.g. GeometryCollection) in this example 53 | return geometry.isWithinDistance(point, MAX_DISTANCE); 54 | } 55 | } 56 | // geometries end 57 | 58 | } 59 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/graph/GraphExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.graph; 2 | 3 | import java.util.Iterator; 4 | 5 | import org.geotools.data.simple.SimpleFeatureCollection; 6 | import org.geotools.data.simple.SimpleFeatureSource; 7 | import org.geotools.feature.FeatureIterator; 8 | import org.geotools.graph.build.GraphBuilder; 9 | import org.geotools.graph.build.line.BasicLineGraphBuilder; 10 | import org.geotools.graph.build.line.BasicLineGraphGenerator; 11 | import org.geotools.graph.build.line.LineGraphGenerator; 12 | import org.geotools.graph.structure.Graph; 13 | import org.geotools.graph.structure.GraphVisitor; 14 | import org.geotools.graph.structure.Graphable; 15 | import org.geotools.graph.traverse.GraphIterator; 16 | import org.geotools.graph.traverse.GraphTraversal; 17 | import org.geotools.graph.traverse.basic.BasicGraphTraversal; 18 | import org.geotools.graph.traverse.basic.SimpleGraphWalker; 19 | import org.geotools.graph.traverse.standard.BreadthFirstIterator; 20 | import org.opengis.feature.Feature; 21 | import org.opengis.feature.FeatureVisitor; 22 | import org.opengis.feature.simple.SimpleFeature; 23 | 24 | public class GraphExamples { 25 | void graphExample() throws Exception { 26 | SimpleFeatureSource featureSource = null; 27 | 28 | // graphExample start 29 | final LineGraphGenerator generator = new BasicLineGraphGenerator(); 30 | SimpleFeatureCollection fc = featureSource.getFeatures(); 31 | 32 | fc.accepts(new FeatureVisitor() { 33 | public void visit(Feature feature) { 34 | generator.add(feature); 35 | } 36 | }, null); 37 | Graph graph = generator.getGraph(); 38 | // graphExample end 39 | 40 | // visitor example start 41 | class OrphanVisitor implements GraphVisitor { 42 | private int count = 0; 43 | public int getCount() { 44 | return count; 45 | } 46 | public int visit(Graphable component) { 47 | Iterator related = component.getRelated(); 48 | if( related.hasNext() == false ){ 49 | // no related components makes this an orphan 50 | count++; 51 | } 52 | return GraphTraversal.CONTINUE; 53 | } 54 | } 55 | OrphanVisitor graphVisitor = new OrphanVisitor(); 56 | 57 | SimpleGraphWalker sgv = new SimpleGraphWalker(graphVisitor); 58 | GraphIterator iterator = new BreadthFirstIterator(); 59 | BasicGraphTraversal bgt = new BasicGraphTraversal(graph, sgv, iterator); 60 | 61 | bgt.traverse(); 62 | 63 | System.out.println("Found orphans: " + graphVisitor.getCount()); 64 | // visitor example end 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/grid/IntersectionBuilder.java: -------------------------------------------------------------------------------- 1 | package org.geotools.grid; 2 | 3 | // IntersectionBuilder start 4 | 5 | import com.vividsolutions.jts.geom.Coordinate; 6 | import com.vividsolutions.jts.geom.Geometry; 7 | import com.vividsolutions.jts.geom.GeometryFactory; 8 | import java.io.IOException; 9 | import java.util.Map; 10 | import org.geotools.data.simple.SimpleFeatureSource; 11 | import org.geotools.factory.CommonFactoryFinder; 12 | import org.geotools.geometry.jts.JTSFactoryFinder; 13 | import org.opengis.feature.simple.SimpleFeatureType; 14 | import org.opengis.filter.Filter; 15 | import org.opengis.filter.FilterFactory2; 16 | 17 | 18 | public class IntersectionBuilder extends GridFeatureBuilder { 19 | final FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2(); 20 | final GeometryFactory gf = JTSFactoryFinder.getGeometryFactory(); 21 | 22 | final SimpleFeatureSource source; 23 | int id = 0; 24 | 25 | public IntersectionBuilder(SimpleFeatureType type, SimpleFeatureSource source) { 26 | super(type); 27 | this.source = source; 28 | } 29 | 30 | public void setAttributes(GridElement el, Map attributes) { 31 | attributes.put("id", ++id); 32 | } 33 | 34 | @Override 35 | public boolean getCreateFeature(GridElement el) { 36 | Coordinate c = ((PolygonElement) el).getCenter(); 37 | Geometry p = gf.createPoint(c); 38 | Filter filter = ff2.intersects(ff2.property("the_geom"), ff2.literal(p)); 39 | boolean result = false; 40 | 41 | try { 42 | result = !source.getFeatures(filter).isEmpty(); 43 | } catch (IOException ex) { 44 | throw new IllegalStateException(ex); 45 | } 46 | 47 | return result; 48 | } 49 | } 50 | 51 | // IntersectionBuilder end 52 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/jdbc/JDBCExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.jdbc; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import org.geotools.data.DataStore; 8 | import org.geotools.data.DataStoreFinder; 9 | 10 | public class JDBCExamples { 11 | 12 | void h2Example() throws IOException { 13 | // h2Example start 14 | Map params = new HashMap(); 15 | params.put("dbtype", "h2"); 16 | params.put("database", "geotools"); 17 | 18 | DataStore datastore = DataStoreFinder.getDataStore(params); 19 | // h2Example end 20 | } 21 | 22 | void h2AbsPathExample() throws IOException { 23 | // h2AbsPathExample start 24 | Map params = new HashMap(); 25 | params.put("dbtype", "h2"); 26 | params.put("database", "/abs/path/to/geotools"); 27 | 28 | DataStore datastore = DataStoreFinder.getDataStore(params); 29 | // h2AbsPathExample end 30 | } 31 | 32 | void h2TcpExample() throws IOException { 33 | // h2TcpExample start 34 | Map params = new HashMap(); 35 | params.put("dbtype", "h2"); 36 | params.put("host", "localhost"); 37 | params.put("port", 9902); 38 | params.put("database", "geotools"); 39 | params.put("passwd", "geotools"); 40 | params.put("passwd", "geotools"); 41 | 42 | DataStore datastore = DataStoreFinder.getDataStore(params); 43 | // h2TcpExample end 44 | } 45 | 46 | void postgisExample() throws IOException { 47 | // postgisExample start 48 | Map params = new HashMap(); 49 | params.put( "dbtype", "postgis"); 50 | params.put( "host", "localhost"); 51 | params.put( "port", 5432); 52 | params.put( "schema", "public"); 53 | params.put( "database", "database"); 54 | params.put( "user", "postgres"); 55 | params.put( "passwd", "postgres"); 56 | 57 | DataStore dataStore=DataStoreFinder.getDataStore(params); 58 | // postgisExample end 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/jts/JTSExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.jts; 2 | 3 | import org.geotools.geometry.jts.JTS; 4 | import org.opengis.referencing.crs.CoordinateReferenceSystem; 5 | 6 | import com.vividsolutions.jts.geom.Coordinate; 7 | 8 | public class JTSExamples { 9 | 10 | void orthodromicDistance() throws Exception { 11 | 12 | Coordinate start = null; 13 | Coordinate end = null; 14 | CoordinateReferenceSystem crs = null; 15 | 16 | // orthodromicDistance start 17 | double distance = JTS.orthodromicDistance(start, end, crs); 18 | int totalmeters = (int) distance; 19 | int km = totalmeters / 1000; 20 | int meters = totalmeters - (km * 1000); 21 | float remaining_cm = (float) (distance - totalmeters) * 10000; 22 | remaining_cm = Math.round(remaining_cm); 23 | float cm = remaining_cm / 100; 24 | 25 | System.out.println("Distance = " + km + "km " + meters + "m " + cm + "cm"); 26 | // orthodromicDistance end 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/main/MainExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.main; 2 | 3 | import org.geotools.data.DataUtilities; 4 | import org.geotools.data.collection.ListFeatureCollection; 5 | import org.geotools.data.simple.SimpleFeatureCollection; 6 | import org.geotools.data.simple.SimpleFeatureIterator; 7 | import org.geotools.feature.DefaultFeatureCollection; 8 | import org.geotools.feature.FeatureCollection; 9 | import org.geotools.feature.FeatureIterator; 10 | import org.opengis.feature.Feature; 11 | import org.opengis.feature.simple.SimpleFeature; 12 | import org.opengis.feature.simple.SimpleFeatureType; 13 | 14 | /** 15 | * Main examples used for sphinx documentation.-+* 16 | * 17 | * @author Jody Garnett 18 | */ 19 | public class MainExamples { 20 | 21 | void exampleDataUtilities() throws Exception { 22 | FeatureCollection collection = null; 23 | 24 | // exampleDataUtilities start 25 | SimpleFeatureCollection features = DataUtilities.simple(collection); 26 | // exampleDataUtilities end 27 | } 28 | 29 | // exampleRetype start 30 | void exampleRetype() throws Exception { 31 | SimpleFeatureType origional = DataUtilities.createType("LINE", "centerline:LineString,name:\"\",id:0"); 32 | SimpleFeatureType modified = DataUtilities.createSubType(origional, new String[]{"centerline"}); 33 | 34 | SimpleFeature feature = DataUtilities.template( origional ); 35 | 36 | SimpleFeature changed = DataUtilities.reType( modified, feature); 37 | } 38 | // exampleRetype end 39 | 40 | void exampleIterator() throws Exception { 41 | SimpleFeatureCollection featureCollection = null; 42 | // exampleIterator start 43 | SimpleFeatureIterator iterator = featureCollection.features(); 44 | try { 45 | while( iterator.hasNext() ){ 46 | SimpleFeature feature = iterator.next(); 47 | // process feature 48 | } 49 | } 50 | finally { 51 | iterator.close(); 52 | } 53 | // exampleIterator end 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/metadata/Example.java: -------------------------------------------------------------------------------- 1 | package org.geotools.metadata; 2 | 3 | import org.geotools.util.Utilities; 4 | 5 | public class Example { 6 | 7 | private Object field1; 8 | private int field2; 9 | private double array[]; 10 | 11 | @Override 12 | public int hashCode() { 13 | int result = 1; 14 | result = Utilities.hash(field1, result); 15 | result = Utilities.hash(field2, result); 16 | result = Utilities.hash(array, result); 17 | 18 | return result; 19 | } 20 | 21 | @Override 22 | public boolean equals(Object obj) { 23 | if (this == obj) { 24 | return true; 25 | } 26 | if (obj == null) { 27 | return false; 28 | } 29 | if (!(obj instanceof Example)) { 30 | return false; 31 | } 32 | Example other = (Example) obj; 33 | return Utilities.equals(field1, other.field1) && Utilities.equals(field2, other.field2) 34 | && Utilities.deepEquals(array, other.array); 35 | } 36 | 37 | @Override 38 | public String toString() { 39 | StringBuilder build = new StringBuilder(); 40 | build.append("Example["); 41 | if (field1 != null) { 42 | build.append(" field1="); 43 | build.append(field1); 44 | } 45 | build.append(" field2="); 46 | build.append(field2); 47 | if (array != null) { 48 | build.append(" array="); 49 | build.append(Utilities.deepToString(array)); 50 | } 51 | build.append("]"); 52 | return build.toString(); 53 | } 54 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/opengis/FeatureExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.opengis; 2 | 3 | import org.geotools.feature.simple.SimpleFeatureBuilder; 4 | import org.geotools.feature.simple.SimpleFeatureTypeBuilder; 5 | import org.geotools.geometry.jts.JTSFactoryFinder; 6 | import org.geotools.referencing.crs.DefaultGeographicCRS; 7 | import org.opengis.feature.simple.SimpleFeature; 8 | import org.opengis.feature.simple.SimpleFeatureType; 9 | 10 | import com.vividsolutions.jts.geom.Coordinate; 11 | import com.vividsolutions.jts.geom.GeometryFactory; 12 | import com.vividsolutions.jts.geom.Point; 13 | 14 | public class FeatureExamples { 15 | 16 | public void javaFlag() { 17 | // javaFlag start 18 | class Flag { 19 | public Point location; 20 | public String name; 21 | public int classification; 22 | public double height; 23 | }; 24 | 25 | GeometryFactory geomFactory = JTSFactoryFinder.getGeometryFactory(); 26 | 27 | Flag here = new Flag(); 28 | here.location = geomFactory.createPoint( new Coordinate(23.3,-37.2) ); 29 | here.name = "Here"; 30 | here.classification = 3; 31 | here.height = 2.0; 32 | // javaFlag end 33 | } 34 | 35 | public void featureFlag() { 36 | // featureFlag start 37 | SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); 38 | b.setName( "Flag" ); 39 | b.setCRS( DefaultGeographicCRS.WGS84 ); 40 | b.add( "location", Point.class ); 41 | b.add( "name", String.class ); 42 | b.add( "classification", Integer.class ); 43 | b.add( "height", Double.class ); 44 | SimpleFeatureType type = b.buildFeatureType(); 45 | 46 | GeometryFactory geomFactory = JTSFactoryFinder.getGeometryFactory(); 47 | 48 | SimpleFeatureBuilder f = new SimpleFeatureBuilder( type ); 49 | f.add( geomFactory.createPoint( new Coordinate(23.3,-37.2) ) ); 50 | f.add("here"); 51 | f.add(3); 52 | f.add(2.0); 53 | SimpleFeature feature = f.buildFeature("fid.1"); 54 | // featureFlag end 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/opengis/StyleExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.opengis; 2 | 3 | import java.awt.Color; 4 | import java.net.URI; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | import org.geotools.factory.CommonFactoryFinder; 9 | import org.geotools.metadata.iso.citation.OnLineResourceImpl; 10 | import org.geotools.styling.StyleFactory; 11 | import org.geotools.styling.StyleFactory2; 12 | import org.opengis.filter.FilterFactory2; 13 | import org.opengis.filter.expression.Expression; 14 | import org.opengis.metadata.citation.OnLineResource; 15 | import org.opengis.style.AnchorPoint; 16 | import org.opengis.style.Displacement; 17 | import org.opengis.style.ExternalMark; 18 | import org.opengis.style.Fill; 19 | import org.opengis.style.Graphic; 20 | import org.opengis.style.GraphicalSymbol; 21 | import org.opengis.style.Mark; 22 | import org.opengis.style.PointSymbolizer; 23 | import org.opengis.style.Stroke; 24 | 25 | public class StyleExamples { 26 | 27 | /** 28 | * This example is limited to just the gt-opengis style interfaces which are immutable once created. 29 | * 30 | * @throws Exception 31 | */ 32 | private void styleFactoryExample() throws Exception { 33 | // styleFactoryExample start 34 | // 35 | org.opengis.style.StyleFactory sf = CommonFactoryFinder.getStyleFactory(); 36 | FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); 37 | 38 | // 39 | // create the graphical mark used to represent a city 40 | Stroke stroke = sf.stroke(ff.literal("#000000"), null, null, null, null, null, null); 41 | Fill fill = sf.fill(null, ff.literal(Color.BLUE), ff.literal(1.0)); 42 | 43 | // OnLineResource implemented by gt-metadata - so no factory! 44 | OnLineResourceImpl svg = new OnLineResourceImpl(new URI("file:city.svg")); 45 | svg.freeze(); // freeze to prevent modification at runtime 46 | 47 | OnLineResourceImpl png = new OnLineResourceImpl(new URI("file:city.png")); 48 | png.freeze(); // freeze to prevent modification at runtime 49 | 50 | // 51 | // List of symbols is considered in order with the rendering engine choosing 52 | // the first one it can handle. Allowing for svg, png, mark order 53 | List symbols = new ArrayList(); 54 | symbols.add(sf.externalGraphic(svg, "svg", null)); // svg preferred 55 | symbols.add(sf.externalGraphic(png, "png", null)); // png preferred 56 | symbols.add(sf.mark(ff.literal("circle"), fill, stroke)); // simple circle backup plan 57 | 58 | Expression opacity = null; // use default 59 | Expression size = ff.literal(10); 60 | Expression rotation = null; // use default 61 | AnchorPoint anchor = null; // use default 62 | Displacement displacement = null; // use default 63 | 64 | // define a point symbolizer of a small circle 65 | Graphic circle = sf.graphic(symbols, opacity, size, rotation, anchor, displacement); 66 | PointSymbolizer pointSymbolizer = sf.pointSymbolizer("point", ff.property("the_geom"), null, 67 | null, circle); 68 | // styleFactoryExample end 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/ObjectFactory.java: -------------------------------------------------------------------------------- 1 | // 2 | // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 3 | // See http://java.sun.com/xml/jaxb 4 | // Any modifications to this file will be lost upon recompilation of the source schema. 5 | // Generated on: 2011.04.10 at 05:20:23 PM EST 6 | // 7 | 8 | 9 | package org.geotools.po; 10 | 11 | import javax.xml.bind.JAXBElement; 12 | import javax.xml.bind.annotation.XmlElementDecl; 13 | import javax.xml.bind.annotation.XmlRegistry; 14 | import javax.xml.namespace.QName; 15 | 16 | 17 | /** 18 | * This object contains factory methods for each 19 | * Java content interface and Java element interface 20 | * generated in the org.geotools.po package. 21 | *

An ObjectFactory allows you to programatically 22 | * construct new instances of the Java representation 23 | * for XML content. The Java representation of XML 24 | * content can consist of schema derived interfaces 25 | * and classes representing the binding of schema 26 | * type definitions, element declarations and model 27 | * groups. Factory methods for each of these are 28 | * provided in this class. 29 | * 30 | */ 31 | @XmlRegistry 32 | public class ObjectFactory { 33 | 34 | private final static QName _Comment_QNAME = new QName("http://www.geotools.org/po", "comment"); 35 | private final static QName _PurchaseOrder_QNAME = new QName("http://www.geotools.org/po", "purchaseOrder"); 36 | 37 | /** 38 | * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.geotools.po 39 | * 40 | */ 41 | public ObjectFactory() { 42 | } 43 | 44 | /** 45 | * Create an instance of {@link USAddress } 46 | * 47 | */ 48 | public USAddress createUSAddress() { 49 | return new USAddress(); 50 | } 51 | 52 | /** 53 | * Create an instance of {@link Items.Item } 54 | * 55 | */ 56 | public Items.Item createItemsItem() { 57 | return new Items.Item(); 58 | } 59 | 60 | /** 61 | * Create an instance of {@link PurchaseOrderType } 62 | * 63 | */ 64 | public PurchaseOrderType createPurchaseOrderType() { 65 | return new PurchaseOrderType(); 66 | } 67 | 68 | /** 69 | * Create an instance of {@link Items } 70 | * 71 | */ 72 | public Items createItems() { 73 | return new Items(); 74 | } 75 | 76 | /** 77 | * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} 78 | * 79 | */ 80 | @XmlElementDecl(namespace = "http://www.geotools.org/po", name = "comment") 81 | public JAXBElement createComment(String value) { 82 | return new JAXBElement(_Comment_QNAME, String.class, null, value); 83 | } 84 | 85 | /** 86 | * Create an instance of {@link JAXBElement }{@code <}{@link PurchaseOrderType }{@code >}} 87 | * 88 | */ 89 | @XmlElementDecl(namespace = "http://www.geotools.org/po", name = "purchaseOrder") 90 | public JAXBElement createPurchaseOrder(PurchaseOrderType value) { 91 | return new JAXBElement(_PurchaseOrder_QNAME, PurchaseOrderType.class, null, value); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/bindings/ItemsBinding.java: -------------------------------------------------------------------------------- 1 | package org.geotools.po.bindings; 2 | 3 | 4 | import javax.xml.namespace.QName; 5 | 6 | import org.geotools.po.ObjectFactory; 7 | import org.geotools.xml.AbstractComplexBinding; 8 | import org.geotools.xml.ElementInstance; 9 | import org.geotools.xml.Node; 10 | 11 | /** 12 | * Binding object for the type http://www.geotools.org/po:Items. 13 | * 14 | *

15 | *

16 |  *	 
17 |  *  <xsd:complexType name="Items">
18 |  *      <xsd:sequence>
19 |  *          <xsd:element maxOccurs="unbounded" minOccurs="0" name="item">
20 |  *              <xsd:complexType name="Items_item">
21 |  *                  <xsd:sequence>
22 |  *                      <xsd:element name="productName" type="xsd:string"/>
23 |  *                      <xsd:element name="quantity">
24 |  *                          <xsd:simpleType>
25 |  *                              <xsd:restriction base="xsd:positiveInteger">
26 |  *                                  <xsd:maxExclusive value="100"/>
27 |  *                              </xsd:restriction>
28 |  *                          </xsd:simpleType>
29 |  *                      </xsd:element>
30 |  *                      <xsd:element name="USPrice" type="xsd:decimal"/>
31 |  *                      <xsd:element minOccurs="0" ref="comment"/>
32 |  *                      <xsd:element minOccurs="0" name="shipDate" type="xsd:date"/>
33 |  *                  </xsd:sequence>
34 |  *                  <xsd:attribute name="partNum" type="SKU" use="required"/>
35 |  *              </xsd:complexType>
36 |  *          </xsd:element>
37 |  *      </xsd:sequence>
38 |  *  </xsd:complexType> 
39 |  *		
40 |  *	  
41 |  *	 
42 | *

43 | * 44 | * @generated 45 | */ 46 | public class ItemsBinding extends AbstractComplexBinding { 47 | 48 | ObjectFactory factory; 49 | public ItemsBinding( ObjectFactory factory ) { 50 | super(); 51 | this.factory = factory; 52 | } 53 | 54 | /** 55 | * @generated 56 | */ 57 | public QName getTarget() { 58 | return PO.Items; 59 | } 60 | 61 | /** 62 | * 63 | * 64 | * 65 | * @generated modifiable 66 | */ 67 | public Class getType() { 68 | return null; 69 | } 70 | 71 | /** 72 | * 73 | * 74 | * 75 | * @generated modifiable 76 | */ 77 | public Object parse(ElementInstance instance, Node node, Object value) 78 | throws Exception { 79 | 80 | //TODO: implement and remove call to super 81 | return super.parse(instance,node,value); 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/bindings/Items_itemBinding.java: -------------------------------------------------------------------------------- 1 | package org.geotools.po.bindings; 2 | 3 | 4 | import javax.xml.namespace.QName; 5 | 6 | import org.geotools.po.ObjectFactory; 7 | import org.geotools.xml.AbstractComplexBinding; 8 | import org.geotools.xml.ElementInstance; 9 | import org.geotools.xml.Node; 10 | 11 | /** 12 | * Binding object for the type http://www.geotools.org/po:Items_item. 13 | * 14 | *

15 | *

16 |  *	 
17 |  *  <xsd:complexType name="Items_item">
18 |  *      <xsd:sequence>
19 |  *          <xsd:element name="productName" type="xsd:string"/>
20 |  *          <xsd:element name="quantity">
21 |  *              <xsd:simpleType>
22 |  *                  <xsd:restriction base="xsd:positiveInteger">
23 |  *                      <xsd:maxExclusive value="100"/>
24 |  *                  </xsd:restriction>
25 |  *              </xsd:simpleType>
26 |  *          </xsd:element>
27 |  *          <xsd:element name="USPrice" type="xsd:decimal"/>
28 |  *          <xsd:element minOccurs="0" ref="comment"/>
29 |  *          <xsd:element minOccurs="0" name="shipDate" type="xsd:date"/>
30 |  *      </xsd:sequence>
31 |  *      <xsd:attribute name="partNum" type="SKU" use="required"/>
32 |  *  </xsd:complexType> 
33 |  *		
34 |  *	  
35 |  *	 
36 | *

37 | * 38 | * @generated 39 | */ 40 | public class Items_itemBinding extends AbstractComplexBinding { 41 | 42 | ObjectFactory factory; 43 | public Items_itemBinding( ObjectFactory factory ) { 44 | super(); 45 | this.factory = factory; 46 | } 47 | 48 | /** 49 | * @generated 50 | */ 51 | public QName getTarget() { 52 | return PO.Items_item; 53 | } 54 | 55 | /** 56 | * 57 | * 58 | * 59 | * @generated modifiable 60 | */ 61 | public Class getType() { 62 | return null; 63 | } 64 | 65 | /** 66 | * 67 | * 68 | * 69 | * @generated modifiable 70 | */ 71 | public Object parse(ElementInstance instance, Node node, Object value) 72 | throws Exception { 73 | 74 | //TODO: implement and remove call to super 75 | return super.parse(instance,node,value); 76 | } 77 | 78 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/bindings/PO.java: -------------------------------------------------------------------------------- 1 | package org.geotools.po.bindings; 2 | 3 | 4 | import java.util.Set; 5 | 6 | import javax.xml.namespace.QName; 7 | 8 | import org.geotools.xml.XSD; 9 | 10 | /** 11 | * This interface contains the qualified names of all the types,elements, and 12 | * attributes in the http://www.geotools.org/po schema. 13 | * 14 | * @generated 15 | */ 16 | public final class PO extends XSD { 17 | 18 | /** singleton instance */ 19 | private static final PO instance = new PO(); 20 | 21 | /** 22 | * Returns the singleton instance. 23 | */ 24 | public static final PO getInstance() { 25 | return instance; 26 | } 27 | 28 | /** 29 | * private constructor 30 | */ 31 | private PO() { 32 | } 33 | 34 | protected void addDependencies(Set dependencies) { 35 | //TODO: add dependencies here 36 | } 37 | 38 | /** 39 | * Returns 'http://www.geotools.org/po'. 40 | */ 41 | public String getNamespaceURI() { 42 | return NAMESPACE; 43 | } 44 | 45 | /** 46 | * Returns the location of 'po.xsd.'. 47 | */ 48 | public String getSchemaLocation() { 49 | return getClass().getResource("po.xsd").toString(); 50 | } 51 | 52 | /** @generated */ 53 | public static final String NAMESPACE = "http://www.geotools.org/po"; 54 | 55 | /* Type Definitions */ 56 | /** @generated */ 57 | public static final QName Items = 58 | new QName("http://www.geotools.org/po","Items"); 59 | /** @generated */ 60 | public static final QName PurchaseOrderType = 61 | new QName("http://www.geotools.org/po","PurchaseOrderType"); 62 | /** @generated */ 63 | public static final QName SKU = 64 | new QName("http://www.geotools.org/po","SKU"); 65 | /** @generated */ 66 | public static final QName USAddress = 67 | new QName("http://www.geotools.org/po","USAddress"); 68 | /** @generated */ 69 | public static final QName Items_item = 70 | new QName("http://www.geotools.org/po","Items_item"); 71 | 72 | /* Elements */ 73 | /** @generated */ 74 | public static final QName comment = 75 | new QName("http://www.geotools.org/po","comment"); 76 | /** @generated */ 77 | public static final QName purchaseOrder = 78 | new QName("http://www.geotools.org/po","purchaseOrder"); 79 | 80 | /* Attributes */ 81 | 82 | } 83 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/bindings/POConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.geotools.po.bindings; 2 | 3 | import org.geotools.xml.Configuration; 4 | import org.picocontainer.MutablePicoContainer; 5 | 6 | /** 7 | * Parser configuration for the http://www.geotools.org/po schema. 8 | * 9 | * @generated 10 | */ 11 | public class POConfiguration extends Configuration { 12 | 13 | /** 14 | * Creates a new configuration. 15 | * 16 | * @generated 17 | */ 18 | public POConfiguration() { 19 | super(PO.getInstance()); 20 | 21 | //TODO: add dependencies here 22 | } 23 | 24 | /** 25 | * Registers the bindings for the configuration. 26 | * 27 | * @generated 28 | */ 29 | protected final void registerBindings( MutablePicoContainer container ) { 30 | //Types 31 | container.registerComponentImplementation(PO.Items,ItemsBinding.class); 32 | container.registerComponentImplementation(PO.PurchaseOrderType,PurchaseOrderTypeBinding.class); 33 | container.registerComponentImplementation(PO.SKU,SKUBinding.class); 34 | container.registerComponentImplementation(PO.USAddress,USAddressBinding.class); 35 | container.registerComponentImplementation(PO.Items_item,Items_itemBinding.class); 36 | 37 | 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/bindings/PurchaseOrderTypeBinding.java: -------------------------------------------------------------------------------- 1 | package org.geotools.po.bindings; 2 | 3 | 4 | import javax.xml.namespace.QName; 5 | 6 | import org.geotools.po.ObjectFactory; 7 | import org.geotools.xml.AbstractComplexBinding; 8 | import org.geotools.xml.ElementInstance; 9 | import org.geotools.xml.Node; 10 | 11 | /** 12 | * Binding object for the type http://www.geotools.org/po:PurchaseOrderType. 13 | * 14 | *

15 | *

16 |  *	 
17 |  *  <xsd:complexType name="PurchaseOrderType">
18 |  *      <xsd:sequence>
19 |  *          <xsd:element name="shipTo" type="USAddress"/>
20 |  *          <xsd:element name="billTo" type="USAddress"/>
21 |  *          <xsd:element minOccurs="0" ref="comment"/>
22 |  *          <xsd:element name="items" type="Items"/>
23 |  *      </xsd:sequence>
24 |  *      <xsd:attribute name="orderDate" type="xsd:date"/>
25 |  *  </xsd:complexType> 
26 |  *		
27 |  *	  
28 |  *	 
29 | *

30 | * 31 | * @generated 32 | */ 33 | public class PurchaseOrderTypeBinding extends AbstractComplexBinding { 34 | 35 | ObjectFactory factory; 36 | public PurchaseOrderTypeBinding( ObjectFactory factory ) { 37 | super(); 38 | this.factory = factory; 39 | } 40 | 41 | /** 42 | * @generated 43 | */ 44 | public QName getTarget() { 45 | return PO.PurchaseOrderType; 46 | } 47 | 48 | /** 49 | * 50 | * 51 | * 52 | * @generated modifiable 53 | */ 54 | public Class getType() { 55 | return null; 56 | } 57 | 58 | /** 59 | * 60 | * 61 | * 62 | * @generated modifiable 63 | */ 64 | public Object parse(ElementInstance instance, Node node, Object value) 65 | throws Exception { 66 | 67 | //TODO: implement and remove call to super 68 | return super.parse(instance,node,value); 69 | } 70 | 71 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/bindings/SKUBinding.java: -------------------------------------------------------------------------------- 1 | package org.geotools.po.bindings; 2 | 3 | import javax.xml.namespace.QName; 4 | 5 | import org.geotools.po.ObjectFactory; 6 | import org.geotools.xml.AbstractSimpleBinding; 7 | import org.geotools.xml.InstanceComponent; 8 | 9 | /** 10 | * Binding object for the type http://www.geotools.org/po:SKU. 11 | * 12 | *

13 | * 14 | *

15 |  *  
16 |  *  <xsd:simpleType name="SKU">
17 |  *      <xsd:restriction base="xsd:string">
18 |  *          <xsd:pattern value="\d{3}-[A-Z]{2}"/>
19 |  *      </xsd:restriction>
20 |  *  </xsd:simpleType> 
21 |  * 	
22 |  *   
23 |  * 
24 | * 25 | *

26 | * 27 | * @generated 28 | */ 29 | public class SKUBinding extends AbstractSimpleBinding { 30 | 31 | ObjectFactory factory; 32 | 33 | public SKUBinding(ObjectFactory factory) { 34 | super(); 35 | this.factory = factory; 36 | } 37 | 38 | /** 39 | * @generated 40 | */ 41 | public QName getTarget() { 42 | return PO.SKU; 43 | } 44 | 45 | /** 46 | * 47 | * 48 | * @generated modifiable 49 | */ 50 | public Class getType() { 51 | return String.class; 52 | } 53 | 54 | /** 55 | * 56 | * 57 | * @generated modifiable 58 | */ 59 | public Object parse(InstanceComponent instance, Object value) throws Exception { 60 | String sku = (String) value; 61 | 62 | if (!sku.matches("\\d{3}-[A-Z]{2}")) { 63 | throw new IllegalArgumentException("Illegal sku format: " + sku); 64 | } 65 | return sku; 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/bindings/USAddressBinding.java: -------------------------------------------------------------------------------- 1 | package org.geotools.po.bindings; 2 | 3 | 4 | import javax.xml.namespace.QName; 5 | 6 | import org.geotools.po.ObjectFactory; 7 | import org.geotools.xml.AbstractComplexBinding; 8 | import org.geotools.xml.ElementInstance; 9 | import org.geotools.xml.Node; 10 | 11 | /** 12 | * Binding object for the type http://www.geotools.org/po:USAddress. 13 | * 14 | *

15 | *

16 |  *	 
17 |  *  <xsd:complexType name="USAddress">
18 |  *      <xsd:sequence>
19 |  *          <xsd:element name="name" type="xsd:string"/>
20 |  *          <xsd:element name="street" type="xsd:string"/>
21 |  *          <xsd:element name="city" type="xsd:string"/>
22 |  *          <xsd:element name="state" type="xsd:string"/>
23 |  *          <xsd:element name="zip" type="xsd:decimal"/>
24 |  *      </xsd:sequence>
25 |  *      <xsd:attribute fixed="US" name="country" type="xsd:NMTOKEN"/>
26 |  *  </xsd:complexType> 
27 |  *		
28 |  *	  
29 |  *	 
30 | *

31 | * 32 | * @generated 33 | */ 34 | public class USAddressBinding extends AbstractComplexBinding { 35 | 36 | ObjectFactory factory; 37 | public USAddressBinding( ObjectFactory factory ) { 38 | super(); 39 | this.factory = factory; 40 | } 41 | 42 | /** 43 | * @generated 44 | */ 45 | public QName getTarget() { 46 | return PO.USAddress; 47 | } 48 | 49 | /** 50 | * 51 | * 52 | * 53 | * @generated modifiable 54 | */ 55 | public Class getType() { 56 | return null; 57 | } 58 | 59 | /** 60 | * 61 | * 62 | * 63 | * @generated modifiable 64 | */ 65 | public Object parse(ElementInstance instance, Node node, Object value) 66 | throws Exception { 67 | 68 | //TODO: implement and remove call to super 69 | return super.parse(instance,node,value); 70 | } 71 | 72 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/po/package-info.java: -------------------------------------------------------------------------------- 1 | // 2 | // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 3 | // See http://java.sun.com/xml/jaxb 4 | // Any modifications to this file will be lost upon recompilation of the source schema. 5 | // Generated on: 2011.04.10 at 05:20:23 PM EST 6 | // 7 | 8 | @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.geotools.org/po", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) 9 | package org.geotools.po; 10 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/process/FeatureProcessExamples.java: -------------------------------------------------------------------------------- 1 | /* 2 | * GeoTools - The Open Source Java GIS Toolkit 3 | * http://geotools.org 4 | * 5 | * (C) 2012, Open Source Geospatial Foundation (OSGeo) 6 | * 7 | * This file is hereby placed into the Public Domain. This means anyone is 8 | * free to do whatever they wish with this file. Use it well and enjoy! 9 | */ 10 | package org.geotools.process; 11 | 12 | import org.geotools.data.simple.SimpleFeatureCollection; 13 | import org.geotools.process.vector.TransformProcess; 14 | 15 | public class FeatureProcessExamples { 16 | 17 | public void exampleTransformProcess(SimpleFeatureCollection featureCollection){ 18 | // transform start 19 | String transform = 20 | "the_geom=the_geom\n"+ 21 | "name=name\n"+ 22 | "area=area( the_geom )"; 23 | 24 | TransformProcess process = new TransformProcess(); 25 | 26 | SimpleFeatureCollection features = process.execute( featureCollection, transform ); 27 | // transform end 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/render/GenerateSVG.java: -------------------------------------------------------------------------------- 1 | /* 2 | * GeoTools - The Open Source Java GIS Toolkit 3 | * http://geotools.org 4 | * 5 | * (C) 2006-2010, Open Source Geospatial Foundation (OSGeo) 6 | * 7 | * This file is hereby placed into the Public Domain. This means anyone is 8 | * free to do whatever they wish with this file. Use it well and enjoy! 9 | */ 10 | package org.geotools.render; 11 | 12 | import java.awt.Dimension; 13 | import java.awt.Rectangle; 14 | import java.io.IOException; 15 | import java.io.OutputStream; 16 | import java.io.OutputStreamWriter; 17 | import java.util.logging.Logger; 18 | 19 | import javax.xml.parsers.DocumentBuilder; 20 | import javax.xml.parsers.DocumentBuilderFactory; 21 | import javax.xml.parsers.ParserConfigurationException; 22 | 23 | import org.apache.batik.svggen.SVGGeneratorContext; 24 | import org.apache.batik.svggen.SVGGraphics2D; 25 | import org.geotools.geometry.jts.ReferencedEnvelope; 26 | import org.geotools.map.MapContent; 27 | import org.geotools.renderer.lite.StreamingRenderer; 28 | import org.w3c.dom.Document; 29 | 30 | /** 31 | * This is a simple support class which allows you to generate an SVG file from a map. 32 | * 33 | * To use, setup a Map object with the layers you want to render, create an envelope for the region 34 | * to be drawn and pass in an OutputStream (probably attached to a new file) for the resulting SVG 35 | * information to be stored in. 36 | * 37 | * Optional you can change the default size of the SVG canvas (in effect increasing the resolution). 38 | * 39 | * @author James Macgill, PennState 40 | * @version 2.8 41 | */ 42 | public class GenerateSVG { 43 | private static Logger LOGGER = org.geotools.util.logging.Logging 44 | .getLogger("org.geotools.svgsupport"); 45 | 46 | // exportSVG start 47 | /** 48 | * Generate an SVG document from the supplied information. Note, use cavasSize first if you want 49 | * to change the default output size. 50 | * 51 | * @param map 52 | * Contains the layers (features + styles) to be rendered 53 | * @param env 54 | * The portion of the map to generate an SVG from 55 | * @param out 56 | * Stream to write the resulting SVG out to (probable should be a new file) 57 | * @param canvasSize 58 | * optional canvas size, will default to 300x300 59 | * @throws IOException 60 | * Should anything go wrong whilst writing to 'out' 61 | * @throws ParserConfigurationException 62 | * If critical XML tools are missing from the classpath 63 | */ 64 | public static void exportSVG(MapContent map, ReferencedEnvelope env, OutputStream out, 65 | Dimension canvasSize) throws IOException, ParserConfigurationException { 66 | if (canvasSize == null) { 67 | canvasSize = new Dimension(300, 300); // default of 300x300 68 | } 69 | Document document = null; 70 | 71 | DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 72 | DocumentBuilder db = dbf.newDocumentBuilder(); 73 | 74 | // Create an instance of org.w3c.dom.Document 75 | document = db.getDOMImplementation().createDocument(null, "svg", null); 76 | 77 | // Set up the map 78 | SVGGeneratorContext ctx1 = SVGGeneratorContext.createDefault(document); 79 | SVGGeneratorContext ctx = ctx1; 80 | ctx.setComment("Generated by GeoTools2 with Batik SVG Generator"); 81 | 82 | SVGGraphics2D g2d = new SVGGraphics2D(ctx, true); 83 | 84 | g2d.setSVGCanvasSize(canvasSize); 85 | 86 | StreamingRenderer renderer = new StreamingRenderer(); 87 | renderer.setMapContent(map); 88 | 89 | Rectangle outputArea = new Rectangle(g2d.getSVGCanvasSize()); 90 | ReferencedEnvelope dataArea = map.getMaxBounds(); 91 | 92 | LOGGER.finest("rendering map"); 93 | renderer.paint(g2d, outputArea, dataArea); 94 | LOGGER.finest("writing to file"); 95 | OutputStreamWriter osw = null; 96 | try { 97 | osw = new OutputStreamWriter(out, "UTF-8"); 98 | g2d.stream(osw); 99 | } finally { 100 | if (osw != null) 101 | osw.close(); 102 | } 103 | 104 | } 105 | // exportSVG end 106 | } 107 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/render/SplatMarkFactory.java: -------------------------------------------------------------------------------- 1 | package org.geotools.render; 2 | 3 | import java.awt.Graphics2D; 4 | import java.awt.Shape; 5 | import java.awt.geom.GeneralPath; 6 | 7 | import org.geotools.renderer.style.MarkFactory; 8 | import org.opengis.feature.Feature; 9 | import org.opengis.filter.expression.Expression; 10 | 11 | class SplatMarkFactory implements MarkFactory { 12 | 13 | private static GeneralPath SPLAT; 14 | 15 | static { 16 | SPLAT = new GeneralPath(GeneralPath.WIND_EVEN_ODD); 17 | SPLAT.moveTo(-0.2f, 0.9f); 18 | SPLAT.lineTo(0.266f, -0.5f); 19 | SPLAT.lineTo(-0.366f, -0.7f); 20 | SPLAT.lineTo(0.4f, 1.12f); 21 | SPLAT.lineTo(0.3f, 1.10f); 22 | } 23 | 24 | public Shape getShape(Graphics2D graphics, Expression symbolUrl, Feature feature) throws Exception { 25 | if (symbolUrl == null) { 26 | // cannot handle a null url 27 | return null; 28 | } 29 | // Evaluate the expression as a String 30 | String wellKnownName = symbolUrl.evaluate(feature, String.class); 31 | 32 | if (wellKnownName != null && wellKnownName.equalsIgnoreCase("splat")) { 33 | return SPLAT; 34 | } 35 | return null; // we do not know this one 36 | } 37 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/swing/JMapPaneExamples.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package org.geotools.swing; 6 | 7 | import org.geotools.geometry.DirectPosition2D; 8 | import org.geotools.swing.event.MapMouseAdapter; 9 | import org.geotools.swing.event.MapMouseEvent; 10 | 11 | /** 12 | * 13 | * @author michael 14 | */ 15 | public class JMapPaneExamples { 16 | 17 | void listenForClicks(JMapPane myMapPane) { 18 | // mouselistener start 19 | myMapPane.addMouseListener(new MapMouseAdapter() { 20 | 21 | @Override 22 | public void onMouseClicked(MapMouseEvent ev) { 23 | // print the screen and world position of the mouse 24 | System.out.println("mouse click at"); 25 | System.out.printf(" screen: x=%d y=%d \n", ev.getX(), ev.getY()); 26 | 27 | DirectPosition2D pos = ev.getWorldPos(); 28 | System.out.printf(" world: x=%.2f y=%.2f \n", pos.x, pos.y); 29 | } 30 | 31 | @Override 32 | public void onMouseEntered(MapMouseEvent ev) { 33 | System.out.println("mouse entered map pane"); 34 | } 35 | 36 | @Override 37 | public void onMouseExited(MapMouseEvent ev) { 38 | System.out.println("mouse left map pane"); 39 | } 40 | }); 41 | // mouselistener end 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/datastore/CSVDataStore.java: -------------------------------------------------------------------------------- 1 | // header start 2 | package org.geotools.tutorial.datastore; 3 | 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.io.Reader; 8 | import java.util.Collections; 9 | import java.util.List; 10 | 11 | import org.geotools.data.Query; 12 | import org.geotools.data.store.ContentDataStore; 13 | import org.geotools.data.store.ContentEntry; 14 | import org.geotools.data.store.ContentFeatureSource; 15 | import org.geotools.feature.NameImpl; 16 | import org.opengis.feature.type.Name; 17 | 18 | import com.csvreader.CsvReader; 19 | 20 | public class CSVDataStore extends ContentDataStore { 21 | // header end 22 | 23 | // constructor start 24 | File file; 25 | 26 | public CSVDataStore( File file ){ 27 | this.file = file; 28 | } 29 | // constructor end 30 | 31 | /** 32 | * Allow read access to file; for our package visibile "friends". 33 | * Please close the reader when done. 34 | * @return CsvReader for file 35 | */ 36 | CsvReader read() throws IOException { 37 | Reader reader = new FileReader(file); 38 | CsvReader csvReader = new CsvReader(reader); 39 | csvReader.close(); 40 | return csvReader; 41 | } 42 | 43 | // createTypeNames start 44 | protected List createTypeNames() throws IOException { 45 | String name = file.getName(); 46 | name = name.substring(0, name.lastIndexOf('.')); 47 | 48 | Name typeName = new NameImpl( name ); 49 | return Collections.singletonList(typeName); 50 | } 51 | // createTypeNames end 52 | 53 | 54 | @Override 55 | protected ContentFeatureSource createFeatureSource(ContentEntry entry) throws IOException { 56 | return new CSVFeatureSource(entry, Query.ALL); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/datastore/CSVFeatureReader.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.datastore; 2 | 3 | import java.io.IOException; 4 | import java.util.NoSuchElementException; 5 | 6 | import org.geotools.data.FeatureReader; 7 | import org.geotools.data.Query; 8 | import org.geotools.data.store.ContentEntry; 9 | import org.geotools.data.store.ContentState; 10 | import org.geotools.feature.simple.SimpleFeatureBuilder; 11 | import org.geotools.geometry.jts.JTSFactoryFinder; 12 | import org.opengis.feature.simple.SimpleFeature; 13 | import org.opengis.feature.simple.SimpleFeatureType; 14 | import org.opengis.feature.type.AttributeDescriptor; 15 | 16 | import com.csvreader.CsvReader; 17 | import com.vividsolutions.jts.geom.Coordinate; 18 | import com.vividsolutions.jts.geom.GeometryFactory; 19 | import com.vividsolutions.jts.geom.Point; 20 | 21 | public class CSVFeatureReader implements FeatureReader { 22 | 23 | private ContentState state; 24 | private Query query; 25 | private CsvReader reader; 26 | private SimpleFeature next; 27 | private SimpleFeatureBuilder builder; 28 | private int row; 29 | private GeometryFactory geometryFactory; 30 | 31 | public CSVFeatureReader(ContentState contentState, Query query) throws IOException { 32 | this.state = contentState; 33 | this.query = query; 34 | CSVDataStore csv = (CSVDataStore) contentState.getEntry().getDataStore(); 35 | reader = csv.read(); // this may throw an IOException if it could not connect 36 | boolean header = reader.readHeaders(); 37 | if (! header ){ 38 | throw new IOException("Unable to read csv header"); 39 | } 40 | builder = new SimpleFeatureBuilder( state.getFeatureType() ); 41 | geometryFactory = JTSFactoryFinder.getGeometryFactory(); 42 | row = 0; 43 | } 44 | 45 | public SimpleFeatureType getFeatureType() { 46 | return (SimpleFeatureType) state.getFeatureType(); 47 | } 48 | 49 | public SimpleFeature next() throws IOException, IllegalArgumentException, 50 | NoSuchElementException { 51 | SimpleFeature feature; 52 | if( next != null ){ 53 | feature = next; 54 | next = null; 55 | } 56 | else { 57 | feature = readFeature(); 58 | } 59 | return feature; 60 | } 61 | 62 | SimpleFeature readFeature() throws IOException { 63 | if( reader == null ){ 64 | throw new IOException("FeatureReader is closed; no additional features can be read"); 65 | } 66 | boolean read = reader.readRecord(); // read the "next" record 67 | if( read == false ){ 68 | close(); // automatic close to be nice 69 | return null; // no additional features are available 70 | } 71 | Coordinate coordinate = new Coordinate(); 72 | for( String column : reader.getHeaders() ){ 73 | String value = reader.get(column); 74 | if( "lat".equalsIgnoreCase(column)){ 75 | coordinate.y = Double.valueOf( value.trim() ); 76 | } 77 | if( "lon".equalsIgnoreCase(column)){ 78 | coordinate.x = Double.valueOf( value.trim() ); 79 | } 80 | builder.set(column, value ); 81 | } 82 | builder.set("Location", geometryFactory.createPoint( coordinate ) ); 83 | 84 | row += 1; 85 | return builder.buildFeature( state.getEntry().getTypeName()+"."+row ); 86 | } 87 | 88 | public boolean hasNext() throws IOException { 89 | if( next != null ){ 90 | return true; 91 | } 92 | else { 93 | next = readFeature(); // read next feature so we can check 94 | return next != null; 95 | } 96 | } 97 | 98 | public void close() throws IOException { 99 | reader.close(); 100 | reader = null; 101 | builder = null; 102 | geometryFactory = null; 103 | next = null; 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/datastore/CSVFeatureSource.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.datastore; 2 | 3 | import java.io.IOException; 4 | 5 | import org.geotools.data.FeatureReader; 6 | import org.geotools.data.Query; 7 | import org.geotools.data.store.ContentEntry; 8 | import org.geotools.data.store.ContentFeatureSource; 9 | import org.geotools.feature.simple.SimpleFeatureTypeBuilder; 10 | import org.geotools.geometry.jts.ReferencedEnvelope; 11 | import org.geotools.referencing.crs.DefaultGeographicCRS; 12 | import org.opengis.feature.simple.SimpleFeature; 13 | import org.opengis.feature.simple.SimpleFeatureType; 14 | 15 | import com.csvreader.CsvReader; 16 | import com.vividsolutions.jts.geom.Point; 17 | 18 | public class CSVFeatureSource extends ContentFeatureSource { 19 | 20 | public CSVFeatureSource(ContentEntry entry, Query query) { 21 | super(entry,query); 22 | } 23 | /** 24 | * Access parent CSVDataStore 25 | */ 26 | public CSVDataStore getDataStore(){ 27 | return (CSVDataStore) super.getDataStore(); 28 | } 29 | 30 | /** 31 | * Implementation that generates the total bounds 32 | * (many file formats record this information in the header) 33 | */ 34 | protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException { 35 | ReferencedEnvelope bounds = new ReferencedEnvelope( getSchema().getCoordinateReferenceSystem() ); 36 | 37 | FeatureReader featureReader = getReaderInternal(query); 38 | try { 39 | while( featureReader.hasNext() ){ 40 | SimpleFeature feature = featureReader.next(); 41 | bounds.include( feature.getBounds() ); 42 | } 43 | } 44 | finally { 45 | featureReader.close(); 46 | } 47 | return bounds; 48 | } 49 | 50 | protected int getCountInternal(Query query) throws IOException { 51 | CsvReader reader = getDataStore().read(); 52 | try { 53 | boolean connect = reader.readHeaders(); 54 | if( connect == false ){ 55 | throw new IOException("Unable to connect"); 56 | } 57 | int count = 0; 58 | while( reader.readRecord() ){ 59 | count += 1; 60 | } 61 | return count; 62 | } 63 | finally { 64 | reader.close(); 65 | } 66 | } 67 | 68 | protected FeatureReader getReaderInternal(Query query) 69 | throws IOException { 70 | return new CSVFeatureReader( getState(), query ); 71 | } 72 | 73 | protected SimpleFeatureType buildFeatureType() throws IOException { 74 | 75 | SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); 76 | builder.setName( entry.getName() ); 77 | 78 | // read headers 79 | CsvReader reader = getDataStore().read(); 80 | try { 81 | boolean success = reader.readHeaders(); 82 | if( success == false ){ 83 | throw new IOException("Header of CSV file not available"); 84 | } 85 | 86 | // we are going to hard code a point location 87 | // columns like lat and lon will be gathered into a 88 | // Point called Location 89 | builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system 90 | builder.add("Location", Point.class ); 91 | 92 | for( String column : reader.getHeaders() ){ 93 | if( "lat".equalsIgnoreCase(column)){ 94 | continue; // skip as it is part of Location 95 | } 96 | if( "lon".equalsIgnoreCase(column)){ 97 | continue; // skip as it is part of Location 98 | } 99 | builder.add(column, String.class); 100 | } 101 | 102 | // build the type (it is immutable and cannot be modified) 103 | final SimpleFeatureType SCHEMA = builder.buildFeatureType(); 104 | return SCHEMA; 105 | } 106 | finally { 107 | reader.close(); 108 | } 109 | } 110 | 111 | 112 | } 113 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/function/AbstractFunction.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.function; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | 6 | import org.geotools.util.Converters; 7 | import org.opengis.filter.capability.FunctionName; 8 | import org.opengis.filter.expression.Expression; 9 | import org.opengis.filter.expression.ExpressionVisitor; 10 | import org.opengis.filter.expression.Function; 11 | import org.opengis.filter.expression.Literal; 12 | 13 | public abstract class AbstractFunction implements Function { 14 | protected final FunctionName name; 15 | protected final List params; 16 | protected final Literal fallback; 17 | 18 | protected AbstractFunction(FunctionName name, List args, Literal fallback) { 19 | this.name = name; 20 | this.params = args; 21 | this.fallback = fallback; 22 | } 23 | public abstract Object evaluate(Object object); 24 | public T evaluate(Object object, Class context) { 25 | Object value = evaluate(object); 26 | return Converters.convert(value, context); 27 | } 28 | public Object accept(ExpressionVisitor visitor, Object extraData) { 29 | return visitor.visit(this, extraData); 30 | } 31 | public String getName() { 32 | return name.getName(); 33 | } 34 | public FunctionName getFunctionName() { 35 | return name; 36 | } 37 | public List getParameters() { 38 | return Collections.unmodifiableList(params); 39 | } 40 | public Literal getFallbackValue() { 41 | return fallback; 42 | } 43 | // helper methods 44 | T eval( Object feature, int index, Class type ){ 45 | Expression expr = params.get(index); 46 | Object value = expr.evaluate( feature, type ); 47 | return type.cast(value); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/function/ExampleFinder.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.function; 2 | 3 | import java.util.Iterator; 4 | import java.util.Set; 5 | 6 | import org.geotools.factory.FactoryCreator; 7 | import org.geotools.factory.FactoryFinder; 8 | import org.geotools.factory.FactoryRegistry; 9 | import org.geotools.factory.GeoTools; 10 | import org.geotools.factory.Hints; 11 | import org.geotools.filter.FunctionFactory; 12 | import org.geotools.resources.LazySet; 13 | import org.opengis.filter.FilterFactory; 14 | 15 | public class ExampleFinder extends FactoryFinder { 16 | 17 | private static FactoryCreator registry; 18 | 19 | private static FactoryRegistry getServiceRegistry() { 20 | assert Thread.holdsLock(ExampleFinder.class); 21 | if (registry == null) { 22 | Class categories[] = new Class[] { FunctionFactory.class }; 23 | registry = new FactoryCreator( categories); 24 | } 25 | return registry; 26 | } 27 | 28 | /** 29 | * Returns a set of all available implementations for the {@link FilterFactory} interface. 30 | * 31 | * @param hints An optional map of hints, or {@code null} if none. 32 | * @return Set of available filter factory implementations. 33 | */ 34 | public static synchronized Set getFilterFactories(Hints hints) { 35 | hints = mergeSystemHints(hints); 36 | Iterator serviceProviders = getServiceRegistry().getServiceProviders( 37 | FunctionFactory.class, null, hints); 38 | return new LazySet(serviceProviders); 39 | } 40 | 41 | /** Allow the classpath to be rescanned */ 42 | public static synchronized void scanForPlugins() { 43 | if (registry != null) { 44 | registry.scanForPlugins(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/function/ExampleFunctionFactory.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.function; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | import org.geotools.feature.NameImpl; 8 | import org.geotools.filter.FunctionFactory; 9 | import org.opengis.feature.type.Name; 10 | import org.opengis.filter.capability.FunctionName; 11 | import org.opengis.filter.expression.Expression; 12 | import org.opengis.filter.expression.Function; 13 | import org.opengis.filter.expression.Literal; 14 | 15 | public class ExampleFunctionFactory implements FunctionFactory { 16 | 17 | public List getFunctionNames() { 18 | List functionList = new ArrayList(); 19 | functionList.add(SnapFunction.NAME); 20 | return Collections.unmodifiableList( functionList ); 21 | } 22 | public Function function(String name, List args, Literal fallback) { 23 | return function(new NameImpl(name), args, fallback); 24 | } 25 | public Function function(Name name, List args, Literal fallback) { 26 | if( SnapFunction.NAME.getFunctionName().equals(name)){ 27 | return new SnapFunction( args, fallback ); 28 | } 29 | return null; // we do not implement that function 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/function/ExampleFunctionFactory2.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.function; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | import org.geotools.feature.NameImpl; 8 | import org.geotools.filter.FunctionFactory; 9 | import org.geotools.filter.capability.FunctionNameImpl; 10 | import org.opengis.feature.type.Name; 11 | import org.opengis.filter.capability.FunctionName; 12 | import org.opengis.filter.expression.Expression; 13 | import org.opengis.filter.expression.Function; 14 | import org.opengis.filter.expression.Literal; 15 | 16 | import com.vividsolutions.jts.geom.Coordinate; 17 | import com.vividsolutions.jts.geom.Geometry; 18 | 19 | public class ExampleFunctionFactory2 implements FunctionFactory { 20 | private ArrayList functionList; 21 | private static FunctionName FIRST = new FunctionNameImpl("first","geometry"); 22 | public synchronized List getFunctionNames() { 23 | if( functionList == null ){ 24 | functionList = new ArrayList(); 25 | functionList.add( FIRST ); 26 | } 27 | return Collections.unmodifiableList( functionList ); 28 | } 29 | public Function function(String name, List args, Literal fallback) { 30 | return function(new NameImpl(name), args, fallback); 31 | } 32 | public Function function(Name name, List args, Literal fallback) { 33 | if(new NameImpl("first").equals(name)){ 34 | return new AbstractFunction( FIRST, args, fallback ){ 35 | public Geometry evaluate(Object object) { 36 | Geometry geom = eval(object, 0, Geometry.class ); 37 | Coordinate coordinate = geom.getCoordinate(); 38 | return geom.getFactory().createPoint(coordinate); 39 | } 40 | }; 41 | } 42 | return null; // we do not implement that function 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/function/SnapFunction.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.function; 2 | 3 | import java.util.List; 4 | 5 | import org.geotools.filter.capability.FunctionNameImpl; 6 | import org.geotools.util.Converters; 7 | import org.opengis.filter.capability.FunctionName; 8 | import org.opengis.filter.expression.Expression; 9 | import org.opengis.filter.expression.ExpressionVisitor; 10 | import org.opengis.filter.expression.Function; 11 | import org.opengis.filter.expression.Literal; 12 | 13 | import com.vividsolutions.jts.geom.Coordinate; 14 | import com.vividsolutions.jts.geom.Geometry; 15 | import com.vividsolutions.jts.geom.Point; 16 | import com.vividsolutions.jts.linearref.LinearLocation; 17 | import com.vividsolutions.jts.linearref.LocationIndexedLine; 18 | 19 | /** 20 | * Quick function that illustrates snapping to a line. 21 | * 22 | * @author jody 23 | */ 24 | public class SnapFunction implements Function { 25 | 26 | static FunctionName NAME = new FunctionNameImpl("snap", Point.class, 27 | FunctionNameImpl.parameter("point",Point.class), 28 | FunctionNameImpl.parameter("line",Geometry.class)); 29 | 30 | private final List parameters; 31 | 32 | private final Literal fallback; 33 | 34 | public SnapFunction(List parameters, Literal fallback) { 35 | if (parameters == null) { 36 | throw new NullPointerException("parameters required"); 37 | } 38 | if (parameters.size() != 2) { 39 | throw new IllegalArgumentException( 40 | "snap( point, line) requires two parameters only"); 41 | } 42 | this.parameters = parameters; 43 | this.fallback = fallback; 44 | } 45 | 46 | public Object evaluate(Object object) { 47 | return evaluate(object, Point.class); 48 | } 49 | 50 | public T evaluate(Object object, Class context) { 51 | Expression pointExpression = parameters.get(0); 52 | Point point = pointExpression.evaluate(object, Point.class); 53 | 54 | Expression lineExpression = parameters.get(1); 55 | Geometry line = lineExpression.evaluate(object, Geometry.class); 56 | 57 | LocationIndexedLine index = new LocationIndexedLine(line); 58 | 59 | LinearLocation location = index.project(point.getCoordinate()); 60 | 61 | Coordinate snap = index.extractPoint(location); 62 | 63 | Point pt = point.getFactory().createPoint(snap); 64 | 65 | return Converters.convert(pt, context); // convert to requested format 66 | } 67 | 68 | public Object accept(ExpressionVisitor visitor, Object extraData) { 69 | return visitor.visit(this, extraData); 70 | } 71 | 72 | public String getName() { 73 | return NAME.getName(); 74 | } 75 | 76 | public FunctionName getFunctionName() { 77 | return NAME; 78 | } 79 | 80 | public List getParameters() { 81 | return parameters; 82 | } 83 | 84 | public Literal getFallbackValue() { 85 | return fallback; 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/graph/Tiger.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.graph; 2 | 3 | import org.geotools.swing.JMapFrame; 4 | 5 | /** 6 | * This is a quick visual example of how to use the graph module using the TIGER roads data. 7 | *

8 | * The gt-graph module builds ontop of core GeoTools concepts (so you should be familiar with DataStore, FeatureCollection, Query, Geometry, 9 | * MapContent prior to starting this tutorial). 10 | *

11 | * This example consists of a *simple* JMapFrame with a number of actions allowing you to load a shapefile; convert it to an internal graph; select 12 | * "waypoints"; and use the way points to calculate a route; use the route to create a FeatureCollection; and display that FeatureCollection as a new 13 | * layer. 14 | *

15 | * 16 | * @author Jody Garnett 17 | */ 18 | public class Tiger extends JMapFrame { 19 | 20 | public Tiger() { 21 | } 22 | 23 | public static void main(String args[]){ 24 | Tiger tiger = new Tiger(); 25 | 26 | tiger.setVisible(true); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Source code examples for the tutorial documentation. 3 | *

4 | * The implementations provided here are spliced into the tutorial documentation using sphinx by 5 | * making use of "markers" placed into the files such as shown below. 6 | *

 7 |  * public void sample(){
 8 |  *     // sample start
 9 |  *     featureCollection.accepts( new FeatureVisitor(){
10 |  *         public void visit( Feature feature ){
11 |  *             System.out.println( feature.getID() );
12 |  *         }
13 |  *     }, null );
14 |  *     // sample end
15 |  * }
16 |  * 
17 | * With this in mind please consider the source code in the contenxt of the documentation; it may 18 | * not always show best practice (if it is part of an example leading up to best practice). 19 | * 20 | * @author Jody Garnett 21 | * @version 2.7 22 | * @since 2.7 23 | */ 24 | package org.geotools.tutorial; -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/process/BufferFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * GeoTools - The Open Source Java GIS Toolkit 3 | * http://geotools.org 4 | * 5 | * (C) 2008, Open Source Geospatial Foundation (OSGeo) 6 | * 7 | * This library is free software; you can redistribute it and/or 8 | * modify it under the terms of the GNU Lesser General Public 9 | * License as published by the Free Software Foundation; 10 | * version 2.1 of the License. 11 | * 12 | * This library is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | * Lesser General Public License for more details. 16 | */ 17 | package org.geotools.tutorial.process; 18 | 19 | import java.util.Collections; 20 | import java.util.Map; 21 | import java.util.TreeMap; 22 | 23 | import org.geotools.data.Parameter; 24 | import org.geotools.feature.NameImpl; 25 | import org.geotools.process.Process; 26 | import org.geotools.process.impl.SingleProcessFactory; 27 | import org.geotools.text.Text; 28 | import org.opengis.util.InternationalString; 29 | 30 | import com.vividsolutions.jts.geom.Geometry; 31 | 32 | /** 33 | * A Buffer process used on a geometry object. 34 | *

35 | * This process is based on the SFSQL specification and implemented by the JTS Topology Suite 36 | * 37 | * @author gdavis 38 | * 39 | * 40 | * 41 | * @source $URL$ 42 | */ 43 | public class BufferFactory extends SingleProcessFactory { 44 | // making parameters available as static constants to help java programmers 45 | /** Geometry for operation */ 46 | static final Parameter GEOM1 = 47 | new Parameter("geom1", Geometry.class, Text.text("Geometry"), Text.text("Geometry to buffer") ); 48 | 49 | /** Buffer amount */ 50 | static final Parameter BUFFER = 51 | new Parameter("buffer", Double.class, Text.text("Buffer Amount"), Text.text("Amount to buffer the geometry by") ); 52 | 53 | /** 54 | * Map used for getParameterInfo; used to describe operation requirements for user 55 | * interface creation. 56 | */ 57 | static final Map> prameterInfo = new TreeMap>(); 58 | static { 59 | prameterInfo.put( GEOM1.key, GEOM1 ); 60 | prameterInfo.put( BUFFER.key, BUFFER ); 61 | } 62 | 63 | static final Parameter RESULT = 64 | new Parameter("result", Geometry.class, Text.text("Result"), Text.text("Result of Geometry.getBuffer( Buffer )") ); 65 | 66 | /** 67 | * Map used to describe operation results. 68 | */ 69 | static final Map> resultInfo = new TreeMap>(); 70 | static { 71 | resultInfo.put( RESULT.key, RESULT ); 72 | } 73 | 74 | public BufferFactory() { 75 | super(new NameImpl("gt", "buffer")); 76 | } 77 | 78 | public Process create(Map parameters) 79 | throws IllegalArgumentException { 80 | return new BufferProcess( this ); 81 | } 82 | 83 | public InternationalString getDescription() { 84 | return Text.text("Buffer a geometry"); 85 | } 86 | 87 | public Map> getParameterInfo() { 88 | return Collections.unmodifiableMap( prameterInfo ); 89 | } 90 | 91 | public Map> getResultInfo( 92 | Map parameters) throws IllegalArgumentException { 93 | return Collections.unmodifiableMap( resultInfo ); 94 | } 95 | 96 | public InternationalString getTitle() { 97 | // please note that this is a title for display purposes only 98 | // finding an specific implementation by name is not possible 99 | return Text.text("Buffer"); 100 | } 101 | 102 | public Process create() throws IllegalArgumentException { 103 | return new BufferProcess( this ); 104 | } 105 | 106 | public boolean supportsProgress() { 107 | return true; 108 | } 109 | 110 | public String getVersion() { 111 | return "1.0.0"; 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/process/BufferFeatureCollectionFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * GeoTools - The Open Source Java GIS Toolkit 3 | * http://geotools.org 4 | * 5 | * (C) 2008, Open Source Geospatial Foundation (OSGeo) 6 | * 7 | * This library is free software; you can redistribute it and/or 8 | * modify it under the terms of the GNU Lesser General Public 9 | * License as published by the Free Software Foundation; 10 | * version 2.1 of the License. 11 | * 12 | * This library is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | * Lesser General Public License for more details. 16 | */ 17 | package org.geotools.tutorial.process; 18 | 19 | import java.util.Map; 20 | 21 | import org.geotools.data.Parameter; 22 | import org.geotools.process.feature.FeatureToFeatureProcessFactory; 23 | import org.geotools.text.Text; 24 | import org.opengis.util.InternationalString; 25 | 26 | /** 27 | * Factory for process which buffers an entire feature collection. 28 | * 29 | * @author Justin Deoliveira, OpenGEO 30 | * @since 2.6 31 | * 32 | * 33 | * 34 | * @source $URL$ 35 | */ 36 | public class BufferFeatureCollectionFactory extends FeatureToFeatureProcessFactory { 37 | 38 | /** Buffer amount */ 39 | public static final Parameter BUFFER = new Parameter("buffer", 40 | Double.class, Text.text("Buffer Amount"), Text.text("Amount to buffer each feature by")); 41 | 42 | public InternationalString getTitle() { 43 | return Text.text("Buffer Features"); 44 | } 45 | 46 | public InternationalString getDescription() { 47 | return Text.text("Buffer each Feature in a Feature Collection"); 48 | } 49 | 50 | @Override 51 | protected void addParameters(Map> parameters) { 52 | parameters.put(BUFFER.key, BUFFER); 53 | } 54 | 55 | public BufferFeatureCollectionProcess create() throws IllegalArgumentException { 56 | return new BufferFeatureCollectionProcess(this); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/process/BufferFeatureCollectionProcess.java: -------------------------------------------------------------------------------- 1 | /* 2 | * GeoTools - The Open Source Java GIS Toolkit 3 | * http://geotools.org 4 | * 5 | * (C) 2008, Open Source Geospatial Foundation (OSGeo) 6 | * 7 | * This library is free software; you can redistribute it and/or 8 | * modify it under the terms of the GNU Lesser General Public 9 | * License as published by the Free Software Foundation; 10 | * version 2.1 of the License. 11 | * 12 | * This library is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | * Lesser General Public License for more details. 16 | */ 17 | package org.geotools.tutorial.process; 18 | 19 | import java.util.Map; 20 | 21 | import org.geotools.feature.simple.SimpleFeatureTypeBuilder; 22 | import org.geotools.process.feature.FeatureToFeatureProcess; 23 | import org.opengis.feature.simple.SimpleFeature; 24 | import org.opengis.feature.simple.SimpleFeatureType; 25 | import org.opengis.feature.type.AttributeDescriptor; 26 | import org.opengis.feature.type.GeometryDescriptor; 27 | 28 | import com.vividsolutions.jts.geom.Geometry; 29 | import com.vividsolutions.jts.geom.MultiPolygon; 30 | import com.vividsolutions.jts.geom.Polygon; 31 | 32 | /** 33 | * Process which buffers an entire feature collection. 34 | * 35 | * @author Justin Deoliveira, OpenGEO 36 | * @since 2.6 37 | * 38 | * 39 | * 40 | * @source $URL$ 41 | */ 42 | public class BufferFeatureCollectionProcess extends FeatureToFeatureProcess { 43 | 44 | /** 45 | * Constructor 46 | * 47 | * @param factory 48 | */ 49 | public BufferFeatureCollectionProcess(BufferFeatureCollectionFactory factory) { 50 | super(factory); 51 | } 52 | 53 | @Override 54 | protected void processFeature(SimpleFeature feature, Map input) throws Exception { 55 | Double buffer = (Double) input.get( BufferFeatureCollectionFactory.BUFFER.key ); 56 | 57 | Geometry g = (Geometry) feature.getDefaultGeometry(); 58 | g = g.buffer( buffer ); 59 | 60 | if(g instanceof Polygon) { 61 | g = g.getFactory().createMultiPolygon(new Polygon[] {(Polygon) g}); 62 | } 63 | 64 | feature.setDefaultGeometry( g ); 65 | } 66 | 67 | @Override 68 | protected SimpleFeatureType getTargetSchema(SimpleFeatureType sourceSchema, Map input) { 69 | SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); 70 | for (AttributeDescriptor ad : sourceSchema.getAttributeDescriptors()) { 71 | GeometryDescriptor defaultGeometry = sourceSchema.getGeometryDescriptor(); 72 | if(ad == defaultGeometry) { 73 | tb.add(ad.getName().getLocalPart(), MultiPolygon.class, defaultGeometry.getCoordinateReferenceSystem()); 74 | } else { 75 | tb.add(ad); 76 | } 77 | } 78 | tb.setName(sourceSchema.getName()); 79 | return tb.buildFeatureType(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/process/BufferProcess.java: -------------------------------------------------------------------------------- 1 | /* 2 | * GeoTools - The Open Source Java GIS Toolkit 3 | * http://geotools.org 4 | * 5 | * (C) 2008, Open Source Geospatial Foundation (OSGeo) 6 | * 7 | * This library is free software; you can redistribute it and/or 8 | * modify it under the terms of the GNU Lesser General Public 9 | * License as published by the Free Software Foundation; 10 | * version 2.1 of the License. 11 | * 12 | * This library is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | * Lesser General Public License for more details. 16 | */ 17 | package org.geotools.tutorial.process; 18 | 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | import org.geotools.process.ProcessFactory; 23 | import org.geotools.process.impl.AbstractProcess; 24 | import org.geotools.text.Text; 25 | import org.geotools.util.NullProgressListener; 26 | import org.opengis.util.ProgressListener; 27 | 28 | import com.vividsolutions.jts.geom.Geometry; 29 | 30 | /** 31 | * Process for adding a buffer around a geometry 32 | * 33 | * @author gdavis 34 | */ 35 | class BufferProcess extends AbstractProcess { 36 | private boolean started = false; 37 | 38 | public BufferProcess(BufferFactory bufferFactory) { 39 | super(bufferFactory); 40 | } 41 | 42 | public ProcessFactory getFactory() { 43 | return factory; 44 | } 45 | 46 | public Map execute(Map input, ProgressListener monitor) { 47 | if (started) 48 | throw new IllegalStateException("Process can only be run once"); 49 | started = true; 50 | 51 | if (monitor == null) 52 | monitor = new NullProgressListener(); 53 | try { 54 | monitor.started(); 55 | monitor.setTask(Text.text("Grabbing arguments")); 56 | monitor.progress(10.0f); 57 | Object value = input.get(BufferFactory.GEOM1.key); 58 | if (value == null) { 59 | throw new NullPointerException("geom1 parameter required"); 60 | } 61 | if (!(value instanceof Geometry)) { 62 | throw new ClassCastException("geom1 requied Geometry, not " + value); 63 | } 64 | Geometry geom1 = (Geometry) value; 65 | 66 | value = input.get(BufferFactory.BUFFER.key); 67 | if (value == null) { 68 | throw new ClassCastException("geom1 requied Geometry, not " + value); 69 | } 70 | if (!(value instanceof Number)) { 71 | throw new ClassCastException("buffer requied number, not " + value); 72 | } 73 | Double buffer = ((Number) value).doubleValue(); 74 | 75 | monitor.setTask(Text.text("Processing Buffer")); 76 | monitor.progress(25.0f); 77 | 78 | if (monitor.isCanceled()) { 79 | return null; // user has canceled this operation 80 | } 81 | 82 | Geometry resultGeom = geom1.buffer(buffer); 83 | 84 | monitor.setTask(Text.text("Encoding result")); 85 | monitor.progress(90.0f); 86 | 87 | Map result = new HashMap(); 88 | result.put(BufferFactory.RESULT.key, resultGeom); 89 | monitor.complete(); // same as 100.0f 90 | 91 | return result; 92 | } catch (Exception eek) { 93 | monitor.exceptionOccurred(eek); 94 | return null; 95 | } finally { 96 | monitor.dispose(); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/process/ProcessTutorial.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.process; 2 | 3 | import org.geotools.process.factory.DescribeParameter; 4 | import org.geotools.process.factory.DescribeProcess; 5 | import org.geotools.process.factory.DescribeResult; 6 | import org.geotools.process.factory.StaticMethodsProcessFactory; 7 | import org.geotools.text.Text; 8 | 9 | import com.vividsolutions.jts.geom.Geometry; 10 | import com.vividsolutions.jts.geom.OctagonalEnvelope; 11 | 12 | public class ProcessTutorial extends StaticMethodsProcessFactory { 13 | // constructor start 14 | public ProcessTutorial() { 15 | super(Text.text("Tutorial"), "tutorial", ProcessTutorial.class); 16 | } 17 | // constructor end 18 | 19 | // octagonalEnvelope start 20 | @DescribeProcess(title = "Octagonal Envelope", description = "Get the octagonal envelope of this Geometry.") 21 | @DescribeResult(description="octagonal of geom") 22 | static public Geometry octagonalEnvelope(@DescribeParameter(name = "geom") Geometry geom) { 23 | return new OctagonalEnvelope(geom).toGeometry(geom.getFactory()); 24 | } 25 | // octagonalEnvelope end 26 | } 27 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/quickstart/Quickstart.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.quickstart; 2 | 3 | import java.io.File; 4 | 5 | import org.geotools.data.FileDataStore; 6 | import org.geotools.data.FileDataStoreFinder; 7 | import org.geotools.data.simple.SimpleFeatureSource; 8 | import org.geotools.map.FeatureLayer; 9 | import org.geotools.map.Layer; 10 | import org.geotools.map.MapContent; 11 | import org.geotools.styling.SLD; 12 | import org.geotools.styling.Style; 13 | import org.geotools.swing.JMapFrame; 14 | import org.geotools.swing.data.JFileDataStoreChooser; 15 | 16 | /** 17 | * Prompts the user for a shapefile and displays the contents on the screen in a map frame. 18 | *

19 | * This is the GeoTools Quickstart application used in documentationa and tutorials. * 20 | */ 21 | public class Quickstart { 22 | 23 | /** 24 | * GeoTools Quickstart demo application. Prompts the user for a shapefile and displays its 25 | * contents on the screen in a map frame 26 | */ 27 | public static void main(String[] args) throws Exception { 28 | // display a data store file chooser dialog for shapefiles 29 | File file = JFileDataStoreChooser.showOpenFile("shp", null); 30 | if (file == null) { 31 | return; 32 | } 33 | 34 | FileDataStore store = FileDataStoreFinder.getDataStore(file); 35 | SimpleFeatureSource featureSource = store.getFeatureSource(); 36 | 37 | // Create a map content and add our shapefile to it 38 | MapContent map = new MapContent(); 39 | map.setTitle("Quickstart"); 40 | 41 | Style style = SLD.createSimpleStyle(featureSource.getSchema()); 42 | Layer layer = new FeatureLayer(featureSource, style); 43 | map.addLayer(layer); 44 | 45 | // Now display the map 46 | JMapFrame.showMap(map); 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/quickstart/QuickstartCache.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.quickstart; 2 | 3 | import java.io.File; 4 | 5 | import org.geotools.data.CachingFeatureSource; 6 | import org.geotools.data.FileDataStore; 7 | import org.geotools.data.FileDataStoreFinder; 8 | import org.geotools.data.simple.SimpleFeatureSource; 9 | import org.geotools.map.FeatureLayer; 10 | import org.geotools.map.Layer; 11 | import org.geotools.map.MapContent; 12 | import org.geotools.styling.SLD; 13 | import org.geotools.styling.Style; 14 | import org.geotools.swing.JMapFrame; 15 | import org.geotools.swing.data.JFileDataStoreChooser; 16 | 17 | /** 18 | * Example used in Quickstart workbook showing how to use a CachingFeatureSource. 19 | *

20 | * This is the GeoTools Quickstart application used in documentationa and tutorials. * 21 | */ 22 | public class QuickstartCache { 23 | 24 | // docs start cache 25 | /** 26 | * This method demonstrates using a memory-based cache to speed up the display (e.g. when 27 | * zooming in and out). 28 | * 29 | * There is just one line extra compared to the main method, where we create an instance of 30 | * CachingFeatureStore. 31 | */ 32 | public static void main(String[] args) throws Exception { 33 | // display a data store file chooser dialog for shapefiles 34 | File file = JFileDataStoreChooser.showOpenFile("shp", null); 35 | if (file == null) { 36 | return; 37 | } 38 | 39 | FileDataStore store = FileDataStoreFinder.getDataStore(file); 40 | SimpleFeatureSource featureSource = store.getFeatureSource(); 41 | 42 | CachingFeatureSource cache = new CachingFeatureSource(featureSource); 43 | 44 | // Create a map content and add our shapefile to it 45 | MapContent map = new MapContent(); 46 | map.setTitle("Using cached features"); 47 | Style style = SLD.createSimpleStyle(featureSource.getSchema()); 48 | Layer layer = new FeatureLayer(cache, style); 49 | map.addLayer(layer); 50 | 51 | // Now display the map 52 | JMapFrame.showMap(map); 53 | } 54 | // docs end cache 55 | } 56 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/quickstart/QuickstartNotes.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.quickstart; 2 | 3 | import java.io.File; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import org.geotools.data.DataStore; 8 | import org.geotools.data.DataStoreFinder; 9 | import org.geotools.data.simple.SimpleFeatureSource; 10 | import org.geotools.swing.data.JFileDataStoreChooser; 11 | 12 | /** 13 | * Additional code examples used by the quickstart tutorial; mostly for the things to try 14 | * section at the end. 15 | */ 16 | class QuickstartNotes { 17 | 18 | public void snipetDataStoreFinder() throws Exception { 19 | // start datastore 20 | File file = JFileDataStoreChooser.showOpenFile("shp", null); 21 | 22 | Map params = new HashMap(); 23 | params.put( "url", file.toURI().toURL() ); 24 | params.put( "create spatial index", false ); 25 | params.put( "memory mapped buffer", false ); 26 | params.put( "charset", "ISO-8859-1" ); 27 | 28 | DataStore store = DataStoreFinder.getDataStore( params ); 29 | SimpleFeatureSource featureSource = store.getFeatureSource( store.getTypeNames()[0] ); 30 | // end datastore 31 | } 32 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/tutorial/wms/WMSLab.java: -------------------------------------------------------------------------------- 1 | package org.geotools.tutorial.wms; 2 | 3 | import java.net.URL; 4 | import java.util.List; 5 | 6 | import javax.swing.JFrame; 7 | import javax.swing.JOptionPane; 8 | 9 | import org.geotools.data.ows.Layer; 10 | import org.geotools.data.wms.WebMapServer; 11 | import org.geotools.map.MapContent; 12 | import org.geotools.map.WMSLayer; 13 | import org.geotools.swing.JMapFrame; 14 | import org.geotools.swing.wms.WMSChooser; 15 | import org.geotools.swing.wms.WMSLayerChooser; 16 | 17 | /** 18 | * This is a Web Map Server "quickstart" doing the minimum required to display 19 | * something on screen. 20 | */ 21 | public class WMSLab extends JFrame { 22 | /** 23 | * Prompts the user for a wms service, connects, and asks for a layer and then 24 | * and displays its contents on the screen in a map frame. 25 | */ 26 | public static void main(String[] args) throws Exception { 27 | // display a data store file chooser dialog for shapefiles 28 | URL capabilitiesURL = WMSChooser.showChooseWMS(); 29 | if( capabilitiesURL == null ){ 30 | System.exit(0); // canceled 31 | } 32 | WebMapServer wms = new WebMapServer( capabilitiesURL ); 33 | 34 | List wmsLayers = WMSLayerChooser.showSelectLayer( wms ); 35 | if( wmsLayers == null ){ 36 | JOptionPane.showMessageDialog(null, "Could not connect - check url"); 37 | System.exit(0); 38 | } 39 | MapContent mapcontent = new MapContent(); 40 | mapcontent.setTitle( wms.getCapabilities().getService().getTitle() ); 41 | 42 | for( Layer wmsLayer : wmsLayers ){ 43 | WMSLayer displayLayer = new WMSLayer(wms, wmsLayer ); 44 | mapcontent.addLayer(displayLayer); 45 | } 46 | // Now display the map 47 | JMapFrame.showMap(mapcontent); 48 | } 49 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/xml/FilterXMLExamples.java: -------------------------------------------------------------------------------- 1 | package org.geotools.xml; 2 | 3 | import org.geotools.filter.FilterFilter; 4 | import org.geotools.filter.FilterHandler; 5 | import org.geotools.gml.GMLFilterDocument; 6 | import org.geotools.gml.GMLFilterGeometry; 7 | import org.opengis.feature.simple.SimpleFeatureType; 8 | import org.opengis.filter.Filter; 9 | import org.xml.sax.InputSource; 10 | import org.xml.sax.XMLReader; 11 | import org.xml.sax.helpers.DefaultHandler; 12 | import org.xml.sax.helpers.XMLReaderFactory; 13 | 14 | @SuppressWarnings("unused") 15 | public class FilterXMLExamples { 16 | 17 | private void saxExample() throws Exception { 18 | SimpleFeatureType featureType = null; 19 | InputSource input = null; 20 | // saxExample start 21 | 22 | class SimpleFilterHandler extends DefaultHandler implements FilterHandler { 23 | public Filter filter; 24 | 25 | public void filter(Filter filter) { 26 | this.filter = filter; 27 | } 28 | } 29 | 30 | SimpleFilterHandler simpleFilterHandler = new SimpleFilterHandler(); 31 | FilterFilter filterFilter = new FilterFilter(simpleFilterHandler, featureType); 32 | GMLFilterGeometry filterGeometry = new GMLFilterGeometry(filterFilter); 33 | GMLFilterDocument filterDocument = new GMLFilterDocument(filterGeometry); 34 | 35 | // parse xml 36 | XMLReader reader = XMLReaderFactory.createXMLReader(); 37 | reader.setContentHandler(filterDocument); 38 | reader.parse(input); 39 | Filter filter = simpleFilterHandler.filter; 40 | // saxExample end 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/xml/GML2Schema.java: -------------------------------------------------------------------------------- 1 | package org.geotools.xml; 2 | 3 | import java.util.List; 4 | 5 | import org.opengis.feature.Feature; 6 | 7 | import com.vividsolutions.jts.geom.Envelope; 8 | 9 | /** 10 | * The following is a placeholder simply to make a UML Diagram. 11 | * @author jody 12 | * 13 | */ 14 | public class GML2Schema { 15 | /** 16 | * An abstract feature provides a set of common properties. A concrete feature type must derive from 17 | * this type and specify additional properties in an application schema. A feature may optionally 18 | * possess an identifying attribute ('fid'). 19 | */ 20 | public static interface AbstractFeatureType { 21 | /** optional */ 22 | public String description(); 23 | 24 | /** optional */ 25 | 26 | public String name(); 27 | 28 | /** optional */ 29 | public Envelope boundedBy(); 30 | } 31 | /** A feature collection contains zero or more featureMember elements. */ 32 | public static interface AbstractFeatureCollectionType { 33 | List featureMemeber(); 34 | } 35 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/xml/TestSchema.java: -------------------------------------------------------------------------------- 1 | package org.geotools.xml; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.opengis.feature.Feature; 7 | 8 | import com.vividsolutions.jts.geom.Envelope; 9 | import com.vividsolutions.jts.geom.Point; 10 | 11 | /** 12 | * The following is a placeholder simply to make a UML Diagram. 13 | * @author jody 14 | * 15 | */ 16 | public class TestSchema { 17 | /** 18 | * An abstract feature provides a set of common properties. A concrete feature type must derive from 19 | * this type and specify additional properties in an application schema. A feature may optionally 20 | * possess an identifying attribute ('fid'). 21 | */ 22 | public static interface TestFeatureType extends GML2Schema.AbstractFeatureType { 23 | public Point pointProperty(); 24 | public int count(); 25 | public Date date(); 26 | } 27 | public static class TestFeature implements TestFeatureType{ 28 | 29 | public String description() { 30 | return null; 31 | } 32 | 33 | public String name() { 34 | return null; 35 | } 36 | 37 | public Envelope boundedBy() { 38 | return null; 39 | } 40 | 41 | public Point pointProperty() { 42 | return null; 43 | } 44 | 45 | public int count() { 46 | return 0; 47 | } 48 | 49 | public Date date() { 50 | return null; 51 | } 52 | 53 | } 54 | 55 | 56 | /** A feature collection contains zero or more featureMember elements. */ 57 | public static interface TestFeatureCollectionType extends GML2Schema.AbstractFeatureCollectionType { 58 | } 59 | 60 | public static class TestFeatureCollection implements TestFeatureCollectionType { 61 | 62 | public List featureMemeber() { 63 | return null; 64 | } 65 | 66 | } 67 | } -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/java/org/geotools/xml/YourCode.java: -------------------------------------------------------------------------------- 1 | package org.geotools.xml; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.geotools.gml.GMLHandlerFeature; 7 | import org.opengis.feature.simple.SimpleFeature; 8 | import org.xml.sax.helpers.XMLFilterImpl; 9 | // yourcode start 10 | public class YourCode extends XMLFilterImpl implements GMLHandlerFeature { 11 | 12 | private List features = new ArrayList(); 13 | 14 | public void feature(SimpleFeature feature) { 15 | features.add(feature); 16 | } 17 | 18 | public List getFeatures() { 19 | return features; 20 | } 21 | } 22 | // yourcode end -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/resources/META-INF/services/org.geotools.process.ProcessFactory: -------------------------------------------------------------------------------- 1 | org.geotools.tutorial.process.ProcessTutorial -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/resources/org/geotools/grid/oz.dbf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/modules/quickstart/src/main/main/resources/org/geotools/grid/oz.dbf -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/resources/org/geotools/grid/oz.fix: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/resources/org/geotools/grid/oz.prj: -------------------------------------------------------------------------------- 1 | GEOGCS["GCS_WGS_1984", DATUM["D_WGS_1984", SPHEROID["WGS_1984", 6378137.0, 298.257223563]], PRIMEM["Greenwich", 0.0], UNIT["degree", 0.017453292519943295], AXIS["Longitude", EAST], AXIS["Latitude", NORTH]] -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/resources/org/geotools/grid/oz.qix: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/modules/quickstart/src/main/main/resources/org/geotools/grid/oz.qix -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/resources/org/geotools/grid/oz.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/modules/quickstart/src/main/main/resources/org/geotools/grid/oz.shp -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/resources/org/geotools/grid/oz.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ianturton/geotools-cookbook/a2364bcf41007dabce93d34eda7c8e8e61015222/modules/quickstart/src/main/main/resources/org/geotools/grid/oz.shx -------------------------------------------------------------------------------- /modules/quickstart/src/main/main/resources/org/geotools/xml/states.xsd: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /modules/styling/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | org.ianturton.cookbook 5 | modules 6 | 0.0.1-SNAPSHOT 7 | 8 | styling 9 | 10 | 11 | org.geotools 12 | gt-main 13 | ${geotools.version} 14 | 15 | 16 | org.geotools 17 | gt-render 18 | ${geotools.version} 19 | 20 | 21 | org.geotools 22 | gt-shapefile 23 | ${geotools.version} 24 | 25 | 26 | org.geotools 27 | gt-epsg-hsql 28 | ${geotools.version} 29 | 30 | 31 | 32 | org.geotools 33 | gt-swing 34 | ${geotools.version} 35 | 36 | 37 | org.ianturton.cookbook 38 | output 39 | 0.0.1-SNAPSHOT 40 | 41 | 42 | -------------------------------------------------------------------------------- /modules/styling/src/main/java/org/ianturton/cookbook/styling/FontManagement.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.styling; 2 | 3 | import java.awt.Color; 4 | import java.awt.GraphicsEnvironment; 5 | 6 | import org.geotools.styling.Font; 7 | import org.geotools.styling.FontImpl; 8 | import org.geotools.styling.Rule; 9 | import org.geotools.styling.SLD; 10 | import org.geotools.styling.Style; 11 | import org.geotools.styling.StyleBuilder; 12 | import org.geotools.styling.TextSymbolizer; 13 | 14 | public class FontManagement { 15 | public String[] listFonts() { 16 | 17 | String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment() 18 | .getAvailableFontFamilyNames(); 19 | return fonts; 20 | } 21 | 22 | public static void main(String[] args) { 23 | // TODO Auto-generated method stub 24 | FontManagement f = new FontManagement(); 25 | String[] fonts = f.listFonts(); 26 | for(String font:fonts){ 27 | System.out.println(font); 28 | } 29 | StyleBuilder builder = new StyleBuilder(); 30 | String attributeName=""; 31 | Font font = builder.createFont(fonts[0], 10.0); 32 | TextSymbolizer textSymb = builder.createTextSymbolizer(Color.black, font , attributeName); 33 | System.out.println(textSymb.getFont().getFamily()); 34 | 35 | Rule rule = builder.createRule(textSymb); 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /modules/styling/src/main/java/org/ianturton/cookbook/styling/TwoAttributes.java: -------------------------------------------------------------------------------- 1 | package org.ianturton.cookbook.styling; 2 | 3 | import java.awt.event.ActionEvent; 4 | import java.io.File; 5 | import java.io.IOException; 6 | 7 | import javax.imageio.ImageIO; 8 | import javax.swing.AbstractAction; 9 | import javax.swing.JOptionPane; 10 | import javax.swing.JToolBar; 11 | 12 | import org.geotools.data.FileDataStore; 13 | import org.geotools.data.FileDataStoreFinder; 14 | import org.geotools.data.simple.SimpleFeatureSource; 15 | import org.geotools.map.FeatureLayer; 16 | import org.geotools.map.Layer; 17 | import org.geotools.map.MapContent; 18 | import org.geotools.styling.SLD; 19 | import org.geotools.styling.Style; 20 | import org.geotools.swing.JMapFrame; 21 | import org.ianturton.cookbook.output.SaveMapAsImage; 22 | import org.opengis.feature.simple.SimpleFeatureType; 23 | 24 | public class TwoAttributes { 25 | private File infile; 26 | private File outFile; 27 | SaveMapAsImage saver = new SaveMapAsImage(); 28 | private JMapFrame frame; 29 | 30 | public TwoAttributes(String[] args) throws IOException { 31 | File file = new File(args[0]); 32 | FileDataStore store = FileDataStoreFinder.getDataStore(file); 33 | SimpleFeatureSource featureSource = store.getFeatureSource(); 34 | SimpleFeatureType schema = featureSource.getSchema(); 35 | System.out.println(schema); 36 | // Create a map content and add our shapefile to it 37 | MapContent mapContent = new MapContent(); 38 | mapContent.setTitle("GeoTools Mapping"); 39 | Style style = SLD.createSimpleStyle(featureSource.getSchema()); 40 | Layer layer = new FeatureLayer(featureSource, style); 41 | mapContent.addLayer(layer); 42 | frame = new JMapFrame(mapContent); 43 | frame.enableStatusBar(true); 44 | frame.enableToolBar(true); 45 | JToolBar toolBar = frame.getToolBar(); 46 | toolBar.addSeparator(); 47 | SaveAction save = new SaveAction("Save"); 48 | toolBar.add(save); 49 | frame.initComponents(); 50 | frame.setSize(1000, 500); 51 | frame.setVisible(true); 52 | } 53 | 54 | public static void main(String[] args) throws IOException { 55 | TwoAttributes me = new TwoAttributes(args); 56 | } 57 | 58 | private class SaveAction extends AbstractAction { 59 | /** 60 | * Private SaveAction 61 | */ 62 | private static final long serialVersionUID = 3071568727121984649L; 63 | 64 | public SaveAction(String text) { 65 | super(text); 66 | } 67 | 68 | @Override 69 | public void actionPerformed(ActionEvent arg0) { 70 | String[] writers = ImageIO.getWriterFormatNames(); 71 | 72 | String format = (String) JOptionPane.showInputDialog(frame, 73 | "Choose output format:", "Customized Dialog", 74 | JOptionPane.PLAIN_MESSAGE, null, writers, "png"); 75 | saver.drawMapToImage(new File("ian." + format), format, 76 | frame.getMapPane()); 77 | 78 | } 79 | 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | org.ianturton 6 | cookbook 7 | 1.0 8 | pom 9 | 10 | cookbook 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 13-SNAPSHOT 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Lesser General Public License (LGPL) 24 | http://www.gnu.org/copyleft/lesser.txt 25 | repo 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | Ian Turton 36 | ianturton 37 | ijturton@gmail.com 38 | Open Source Geospatial Foundation 39 | 40 | 41 | 42 | 43 | 44 | modules 45 | book 46 | 47 | 48 | 49 | 50 | 51 | 52 | org.apache.maven.plugins 53 | maven-compiler-plugin 54 | 55 | 1.7 56 | 1.7 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | maven2-repository.dev.java.net 65 | Java.net repository 66 | http://download.java.net/maven/2 67 | 68 | 69 | 70 | osgeo 71 | Open Source Geospatial Foundation Repository 72 | http://download.osgeo.org/webdav/geotools/ 73 | 74 | 75 | 76 | true 77 | 78 | boundless 79 | Boundless Maven Repository 80 | http://repo.boundlessgeo.com/main 81 | 82 | 83 | 84 | true 85 | 86 | opengeo 87 | OpenGeo Maven Repository 88 | http://repo.opengeo.org 89 | 90 | 91 | 92 | --------------------------------------------------------------------------------