예제 #1
0
        public void ImportGeoJSONObject()
        {
            GeoJSONObject     geoJSONObject     = GeoJSONObject.ImportGeoJSON(File.ReadAllText("locationsAutoGenerated.json"));
            FeatureCollection featureCollection = (FeatureCollection)geoJSONObject;

            Assert.AreEqual(featureCollection.Features.ToArray().Length, 3);
        }
예제 #2
0
 private IEnumerator LoadJSON(string txt)
 {
     //Debug.Log("Enter LoadJSON");
     Collection = GeoJSONObject.Deserialize(txt);
     yield return(loadedJSON = true);
     //Debug.Log("Exit LoadJSON");
 }
예제 #3
0
    /// <summary>
    /// Called when the "Import" button is clicked
    /// </summary>
    private void OnWizardCreate()
    {
        GameObject parentGameObject = new GameObject();

        parentGameObject.name = this.ParentName;

        try
        {
            FeatureCollection features = GeoJSONObject.Deserialize(this.GeoJSONSource.text);

            MapBounds bounds = features.bbox;
            bounds.ProjectToWebMercator();
            bounds.SetScale(this.HorizontalScale);

            this.UpdateCameraParameters(bounds.Center.ToVector3(), this.HorizontalScale, this.VerticalScale);

            foreach (FeatureObject ftr in features.features)
            {
                MapFeature feature = new MapFeature(ftr.properties[this.ObjectIDFieldName]);

                List <Vertex> vertices = ftr.geometry.AllPositions().ConvertAll((v) => new Vertex(v.latitude, v.longitude, 0.0));

                feature.SetAttributes(ftr.properties);
                feature.SetGeometry(EnumGeometryType.Polygon, vertices);

                if (feature.Geometry.IsEmpty)
                {
                    continue;
                }

                feature.Geometry.ProjectToWebMercator();
                feature.Geometry.SetScale(this.HorizontalScale);

                Vector3 cityOrigin = feature.Geometry.GetCentroid();

                GameObject go = feature.ToGameObject();
                go.transform.position = cityOrigin - bounds.Center.ToVector3();
                go.transform.parent   = parentGameObject.transform;

                Material material = new Material(Shader.Find("Standard"));
                material.color = Color.gray;// UnityEngine.Random.ColorHSV();
                go.GetComponent <Renderer>().material = material;

                if (this.Extrude)
                {
                    float height = feature.Attributes.Get <float>(this.ExtrudeField);

                    if (height > 0)
                    {
                        height = height * this.ExtrudeFactor;
                        MeshExtrusion.Extrude(go, height, this.InvertFaces);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
        }
    }
        private void AssertIsEqualToGeoJsonFile(GeoJSONObject geoJsonObject, string fileName, Type expectedType)
        {
            var serialized = JsonConvert.SerializeObject(geoJsonObject);

            Debug.WriteLine(serialized);
            var json = JsonConvert.SerializeObject(GetObjectFromJson(fileName, expectedType));

            serialized.ShouldBe(json);
        }
예제 #5
0
        /// <summary>
        /// Translate a GEOJSONObject to the corresponding SqlGeography. Please note that without any additional configuration,
        /// a FeatureCollection will turn into a GeometryCollection and the geometry of each feature will be added to that collection.
        /// </summary>
        public static SqlGeography Translate(GeoJSONObject geoJsonObject)
        {
            AssertValidity();
            var visitor = new GeoJsonToSqlGeographyObjectWalker();
            var walker  = new GeoJsonObjectWalker(geoJsonObject);

            walker.CarryOut(visitor);
            return(visitor.ConstructedGeography);
        }
예제 #6
0
        private void DeserializeGeoJson()
        {
            var geoJSON            = new GeoJSONObject(this.Component.geoJsonFile.text);
            var filteredGeometries =
                from feature in geoJSON.FeatureCollection.Features
                where this.Component.featureTypeFilter == "" || feature.Properties.Type == this.Component.featureTypeFilter
                select feature.Geometry as PointGeometry;

            this.m_geometries = filteredGeometries.ToList();
        }
예제 #7
0
        /// <summary>
        /// Parses a geometry object.
        /// </summary>
        /// <param name="jObject">The object token.</param>
        private IGeometryObject ParseGeometryObject(JObject jObject)
        {
            JProperty typeProperty = jObject.Property("type");

            if (typeProperty != null)
            {
                string        geometryTypeEx = typeProperty.Value.ToObjectOrDefault <string>().ToLower();
                GeoJSONObject geoJSONObject  = null;

                switch (geometryTypeEx)
                {
                case "geometrycollection":
                    geoJSONObject = ParseGeometryCollection(jObject.Property("geometries").Value);
                    break;

                case "multilinestring":
                    geoJSONObject = ParseMultiLineStringEx(jObject.Property("coordinates").Value);
                    break;

                case "linestring":
                    geoJSONObject = ParseLineString(jObject.Property("coordinates").Value);
                    break;

                case "multipolygon":
                    geoJSONObject = ParseMultiPolygon(jObject.Property("coordinates").Value);
                    break;

                case "polygon":
                    geoJSONObject = ParsePolygon(jObject.Property("coordinates").Value);
                    break;

                case "multipoint":
                    geoJSONObject = ParseMultiPoint(jObject.Property("coordinates").Value);
                    break;

                case "point":
                    geoJSONObject = ParsePoint(jObject.Property("coordinates").Value);
                    break;
                }

                ParseBoundingBox(geoJSONObject, jObject.Property("bbox"));
                if (jObject.Property("crs") != null)
                {
                    geoJSONObject.CRS = CoordinateReferenceSystemConverter.ParseCrs(jObject.Property("crs").Value.ToObjectOrDefault <JObject>());
                }

                return((IGeometryObject)geoJSONObject);
            }
            throw new ParsingException();
        }
예제 #8
0
        private void DeserializeGeoJson()
        {
            var geoJSON          = new GeoJSONObject(this.Component.geoJsonFile.text);
            var filteredFeatures =
                from feature in geoJSON.FeatureCollection.Features
                select feature;

            if (this.Component.featureTypeFilter != null && this.Component.featureTypeFilter != "")
            {
                filteredFeatures =
                    from feature in filteredFeatures
                    where feature.Properties.Type == this.Component.featureTypeFilter
                    select feature;
            }
            this.m_features = filteredFeatures.ToList();
        }
예제 #9
0
        /// <summary>
        /// Imports GeoJSON and adds the new features to the feature list
        /// </summary>
        /// <param name="contents">A serialised GeoJSON object</param>
        /// <returns>Number of features successfully imported</returns>
        public async Task <int> ImportRawContents(string contents)
        {
            GeoJSONObject importedGeoJSON = GeoJSONObject.ImportGeoJSON(contents);

            if (importedGeoJSON == null)
            {
                throw new ArgumentException("Import data does not contain valid GeoJSON");
            }

            return(importedGeoJSON.Type switch
            {
                GeoJSONType.Point => await ImportItem(new Feature((Models.Point)importedGeoJSON)) ? 1 : 0,
                GeoJSONType.LineString => await ImportItem(new Feature((LineString)importedGeoJSON)) ? 1 : 0,
                GeoJSONType.Polygon => await ImportItem(new Feature((Polygon)importedGeoJSON)) ? 1 : 0,
                GeoJSONType.Feature => await ImportItem((Feature)importedGeoJSON) ? 1 : 0,
                GeoJSONType.FeatureCollection => await ImportItems(((FeatureCollection)importedGeoJSON).Features),
                _ => throw new ArgumentException("Import data does not contain a supported GeoJSON type."),
            });
예제 #10
0
        /// <summary>
        /// Parses the bounding box.
        /// </summary>
        /// <remarks>
        /// The bounding boxes will look like this "bbox": [100.0, 0.0, 105.0, 1.0]
        /// </remarks>
        /// <param name="geoJSONObject">The geo JSON object.</param>
        /// <param name="jProperty">The json.net property object.</param>
        private void ParseBoundingBox(GeoJSONObject geoJSONObject, JProperty jProperty)
        {
            if (jProperty == null || !jProperty.HasValues)
            {
                return;
            }

            if (jProperty.Value.Type == JTokenType.Array)
            {
                JArray   bboxArray = jProperty.Value.Value <JArray>();
                double[] bbox      = new double[bboxArray.Count];
                for (int i = 0; i < bboxArray.Count; i++)
                {
                    bbox[i] = bboxArray[i].ToObjectOrDefault <double>();
                }

                geoJSONObject.BoundingBoxes = bbox;
            }
        }
예제 #11
0
        private static GeoJSONObject ReadGeometryTaggedText(WktStreamTokenizer tokenizer)
        {
            tokenizer.NextToken();
            var           type     = tokenizer.GetStringValue().ToUpper();
            GeoJSONObject geometry = null;

            switch (type)
            {
            case "POINT":
                geometry = ReadPointText(tokenizer);
                break;

            case "LINESTRING":
                geometry = ReadLineStringText(tokenizer);
                break;

            /*case "MULTIPOINT":
             *      geometry = ReadMultiPointText(tokenizer);
             *      break;*/
            /*case "MULTILINESTRING":
             *      geometry = ReadMultiLineStringText(tokenizer);
             *      break;*/
            case "POLYGON":
                geometry = ReadPolygonText(tokenizer);
                break;

            case "MULTIPOLYGON":
                geometry = ReadMultiPolygonText(tokenizer);
                //geometry = ReadMultiPolygonText(tokenizer);
                break;

            /*case "GEOMETRYCOLLECTION":
             *      geometry = ReadGeometryCollectionText(tokenizer);
             *      break;*/
            default:
                throw new Exception(String.Format(new CultureInfo("en-US", false).NumberFormat, "Geometrytype '{0}' is not supported.",
                                                  type));
            }
            return(geometry);
        }
예제 #12
0
        public async Task ImportFeatureList()
        {
            try
            {
                FeatureCollection featureCollection = (FeatureCollection)GeoJSONObject.ImportGeoJSON(Constants.FeaturesFileContents);
                _ = await FeatureStore.ImportItems(featureCollection.Features);
            }
            catch
            {
                bool result = await NavigationService.ShowAlert("Feature List Error", "Groundsman was unable to load your saved features. Would you like to export the corrupted features?", true);

                if (result)
                {
                    await Share.RequestAsync(new ShareFileRequest
                    {
                        Title = "Groundsman Feature List (Corrupted)",
                        File  = new ShareFile(Constants.FEATURES_FILE, "application/json"),
                    });
                }
                await FeatureStore.ResetItems();
            }
        }
예제 #13
0
        public static GeoJsonParseResult TryParse(IJsonValue value, IJsonSerializer serializer, out GeoJSONObject geoJSON)
        {
            Guard.NotNull(serializer, nameof(serializer));
            Guard.NotNull(value, nameof(value));

            geoJSON = null !;

            if (value is JsonObject geoObject)
            {
                try
                {
                    using (var stream = DefaultPools.MemoryStream.GetStream())
                    {
                        serializer.Serialize(value, stream, true);

                        stream.Position = 0;

                        geoJSON = serializer.Deserialize <GeoJSONObject>(stream, null, leaveOpen: true);

                        return(GeoJsonParseResult.Success);
                    }
                }
                catch
                {
                    if (!geoObject.TryGetValue <JsonNumber>("latitude", out var lat) || !lat.Value.IsBetween(-90, 90))
                    {
                        return(GeoJsonParseResult.InvalidLatitude);
                    }

                    if (!geoObject.TryGetValue <JsonNumber>("longitude", out var lon) || !lon.Value.IsBetween(-180, 180))
                    {
                        return(GeoJsonParseResult.InvalidLongitude);
                    }

                    geoJSON = new Point(new Position(lat.Value, lon.Value));

                    return(GeoJsonParseResult.Success);
                }
            }

            return(GeoJsonParseResult.InvalidValue);
        }
예제 #14
0
        public override void Load()
        {
            if (Data == null)
            {
                return;
            }

            // Load the geoJSON file
            FeatureCollection collection = GeoJSONObject.Deserialize(Data.text);

            // Create a list of lists that we will be populating with our fortified shape data
            List <List <string> > geoData = new List <List <string> >();

            for (int i = 0; i < 5; i++)
            {
                geoData.Add(new List <string>());
            }

            // Create another dictionary of lists that will contain the properties that are encoded within the geoJSON file
            Dictionary <string, List <string> > propertyData = new Dictionary <string, List <string> >();

            foreach (string property in collection.features[0].properties.Keys)
            {
                propertyData[property] = new List <string>();
            }

            for (int i = 0; i < collection.features.Count; i++)
            {
                FeatureObject feature = collection.features[i];

                int order = 0;

                if (feature.geometry.type == "Polygon")
                {
                    PolygonGeometryObject geometry = (PolygonGeometryObject)feature.geometry;

                    for (int j = 0; j < geometry.coordinates.Count; j++)
                    {
                        List <PositionObject> positionObjects = geometry.coordinates[j];

                        for (int k = 0; k < positionObjects.Count - 1; k++)     // Ignore last coordinate
                        {
                            PositionObject point = positionObjects[k];
                            geoData[0].Add(point.longitude.ToString());
                            geoData[1].Add(point.latitude.ToString());
                            geoData[2].Add(order.ToString());
                            geoData[3].Add(i.ToString());
                            geoData[4].Add(j.ToString());

                            foreach (var property in feature.properties)
                            {
                                propertyData[property.Key].Add(property.Value);
                            }

                            order++;
                        }
                    }
                }
                else if (feature.geometry.type == "MultiPolygon")
                {
                    MultiPolygonGeometryObject geometry = (MultiPolygonGeometryObject)feature.geometry;

                    for (int j = 0; j < geometry.coordinates.Count; j++)
                    {
                        List <List <PositionObject> > polygon = geometry.coordinates[j];

                        for (int k = 0; k < polygon.Count; k++)
                        {
                            List <PositionObject> positionObjects = polygon[k];

                            for (int l = 0; l < positionObjects.Count - 1; l++)     // Ignore last coordinate
                            {
                                PositionObject point = positionObjects[l];
                                geoData[0].Add(point.longitude.ToString());
                                geoData[1].Add(point.latitude.ToString());
                                geoData[2].Add(order.ToString());
                                geoData[3].Add(i.ToString());
                                geoData[4].Add(j.ToString());

                                foreach (var property in feature.properties)
                                {
                                    propertyData[property.Key].Add(property.Value);
                                }

                                order++;
                            }
                        }
                    }
                }
            }

            // Populate data structures
            originalData = new List <string[]>();
            attributes   = new List <DataAttribute>();

            foreach (var list in geoData)
            {
                originalData.Add(list.ToArray());
            }

            attributes.Add(new DataAttribute("Longitude", IATKDataType.Numeric, originalData[0].ToArray()));
            attributes.Add(new DataAttribute("Latitude", IATKDataType.Numeric, originalData[1].ToArray()));
            attributes.Add(new DataAttribute("Order", IATKDataType.Numeric, originalData[2].ToArray()));
            attributes.Add(new DataAttribute("Group", IATKDataType.Factor, originalData[3].ToArray()));
            attributes.Add(new DataAttribute("Piece", IATKDataType.Factor, originalData[4].ToArray()));


            foreach (var property in propertyData)
            {
                string[]     array    = property.Value.ToArray();
                IATKDataType dataType = DataTypesExtension.InferFromString(array[0]);
                originalData.Add(array);
                attributes.Add(new DataAttribute(property.Key, dataType, array));
            }

            DataCount = attributes[0].Length;
        }
 public GeoJsonObjectWalker(GeoJSONObject geoJsonObject)
 {
     _geoJsonObject = geoJsonObject;
 }