Esempio n. 1
0
def write_geojson(best_point, all_the_points):
    all_pt_style = {"name": "Various Intersections", "marker-color": "#FF0000"}
    best_pt_style = {"name": "Most Likely TX Location", "marker-color": "#00FF00"}
    if all_the_points != None:
        all_the_points = Feature(properties = all_pt_style, geometry = MultiPoint(tuple(all_the_points)))
        with open(geofile, "w") as file1:
            if best_point != None:
                reversed_best_point = []
                for x in best_point:
                    reversed_best_point.append(Reverse(x))
                best_point = Feature(properties = best_pt_style, geometry = MultiPoint(tuple(reversed_best_point)))
                file1.write(str(FeatureCollection([best_point, all_the_points])))
            else:
                file1.write(str(FeatureCollection([all_the_points])))
        print(f"Wrote file {geofile}")
Esempio n. 2
0
def test_bbox_multi_point():
    mp = MultiPoint([(-155.52, 19.61), (-156.22, 20.74), (-157.97, 21.46)])
    bb = bbox(mp)
    assert bb[0] == -157.97
    assert bb[1] == 19.61
    assert bb[2] == -155.52
    assert bb[3] == 21.46
Esempio n. 3
0
def process(data, threshold, size):
    cord_lst, cord_id = extract_cords(data)
    clusters, n_clusters = dbscan(cord_lst, threshold, size)
    #colorset
    rand_color = randomcolor.RandomColor()
    color_lst = rand_color.generate(count=n_clusters)
    #generate geojson
    features = []
    for i in range(len(clusters)):
        if clusters[i].size:
            cords = clusters[i].tolist()
            cords_set = set()
            for cord in cords:
                cords_set.add(tuple(cord))
            if i != 0:
                top_keywords = process_text(list(cords_set), cord_id)
                summary = "Number of posts: " + str(
                    len(cords)) + ", Top 10 Keywords:"
                for keyword, frequency in top_keywords:
                    summary = summary + " " + keyword + "(" + str(
                        frequency) + ")"
            cord_mp = MultiPoint(list(cords_set))
            if i == 0:
                feature = Feature(geometry=cord_mp,
                                  properties={"color": "#826969"})
            else:
                feature = Feature(geometry=cord_mp,
                                  properties={
                                      "color": color_lst[i - 1],
                                      "summary": summary
                                  })
            features.append(feature)
    feature_collection = FeatureCollection(features)
    return feature_collection
Esempio n. 4
0
    def to_GeoJSON(self):
        properties = {}
        coord_list = []

        for k,v in self.__dict__.items():
            if v != '' and k != "GeoJSON":
                properties[k] = v
            
        try:
            if self.Actor1Geo_Lat != '' and self.Actor1Geo_Long:
                coord_list.append((self.Actor1Geo_Long,self.Actor1Geo_Lat))
        except:
            pass

        try:
            if self.Actor2Geo_Lat != '' and self.Actor2Geo_Long:
                coord_list.append((self.Actor2Geo_Long,self.Actor2Geo_Lat))
        except:
            pass

        try:
            if self.ActionGeo_Lat != '' and self.ActionGeo_Long:
                coord_list.append((self.ActionGeo_Long,self.ActionGeo_Lat))
        except:
            pass

        geom = MultiPoint(coord_list)
        self.geojson = Feature(geometry=geom, properties=properties)

        return self.geojson
Esempio n. 5
0
def test_geojson(test_coordinates):
    # GeoJSON fixture used for the tests (converted from test_coordinates)
    lat_1, lng_1, lat_2, lng_2 = test_coordinates
    coords = [(lng_1, lat_1), (lng_2, lat_2)]
    f1 = Feature(geometry=LineString(coords))
    f2 = Feature(geometry=MultiPoint(coords))
    return FeatureCollection([f1, f2])
Esempio n. 6
0
    def write_output(self, step_num, islast_step=False):
        'dump data in geojson format'
        super(TrajectoryGeoJsonOutput,
              self).write_output(step_num, islast_step)

        if not self._write_step:
            return None

        # one feature per element client; replaced with multipoint
        # because client performance is much more stable with one
        # feature per step rather than (n) features per step.features = []
        features = []
        for sc in self.cache.load_timestep(step_num).items():
            time = date_to_sec(sc.current_time_stamp)
            position = self._dataarray_p_types(sc['positions'])
            status = self._dataarray_p_types(sc['status_codes'])
            sc_type = 'uncertain' if sc.uncertain else 'forecast'

            # break elements into multipoint features based on their status code
            # evaporated : 10
            # in_water : 2
            # not_released : 0
            # off_maps : 7
            # on_land : 3
            # to_be_removed : 12
            points = {}
            for ix, pos in enumerate(position):
                st_code = status[ix]

                if st_code not in points:
                    points[st_code] = []

                points[st_code].append(pos[:2])

            for k in points:
                feature = Feature(geometry=MultiPoint(points[k]),
                                  id="1",
                                  properties={
                                      'sc_type': sc_type,
                                      'status_code': k,
                                  })
                if sc.uncertain:
                    features.insert(0, feature)
                else:
                    features.append(feature)

        geojson = FeatureCollection(features)
        # default geojson should not output data to file
        # read data from file and send it to web client
        output_info = {
            'time_stamp': sc.current_time_stamp.isoformat(),
            'feature_collection': geojson
        }

        if self.output_dir:
            output_filename = self.output_to_file(geojson, step_num)
            output_info.update({'output_filename': output_filename})

        return output_info
Esempio n. 7
0
def dump_flight_to_geojson(flight, geojson_filename_local):
    """Dumps the flight to geojson format. """

    from geojson import Point, Feature, FeatureCollection, MultiPoint, MultiLineString, dump

    assert flight.valid

    #TODO write objects to the geojson form the flight object
    min_lat = flight.takeoff_fix.lat
    min_lon = flight.takeoff_fix.lon
    max_lat = flight.takeoff_fix.lat
    max_lon = flight.takeoff_fix.lon

    bbox = [[min_lat, min_lon], [max_lat, max_lon]]

    features = []
    #features.append(Feature(geometry=point, properties={"country": "Spain"}))

    takeoff = Point((flight.takeoff_fix.lon, flight.takeoff_fix.lat))
    features.append(
        Feature(geometry=takeoff, properties={"TakeOff": "TakeOff"}))
    bbox = checkbbox(flight.takeoff_fix.lat, flight.takeoff_fix.lon, bbox)
    landing = Point((flight.landing_fix.lon, flight.landing_fix.lat))
    features.append(
        Feature(geometry=landing, properties={"Landing": "Landing"}))
    bbox = checkbbox(flight.landing_fix.lat, flight.landing_fix.lon, bbox)

    thermals = []
    for i, thermal in enumerate(flight.thermals):
        #        add_point(name="thermal_%02d" % i, fix=thermal.enter_fix)
        thermals.append((thermal.enter_fix.lon, thermal.enter_fix.lat))
        #        add_point(name="thermal_%02d_END" % i, fix=thermal.exit_fix)
        thermals.append((thermal.exit_fix.lon, thermal.exit_fix.lat))

        bbox = checkbbox(thermal.enter_fix.lat, thermal.enter_fix.lon, bbox)
        bbox = checkbbox(thermal.exit_fix.lat, thermal.exit_fix.lon, bbox)

    thermals_multipoint = MultiPoint(thermals)
    features.append(Feature(geometry=thermals_multipoint))

    route = []
    for fix in flight.fixes:
        route.append((fix.lon, fix.lat))

        bbox = checkbbox(fix.lat, fix.lon, bbox)

    route_multilinestring = MultiLineString([route])
    features.append(
        Feature(geometry=route_multilinestring, properties={"Track": "Track"}))

    # add more features...
    # features.append(...)

    feature_collection = FeatureCollection(features)

    with open(geojson_filename_local, 'w') as f:
        dump(feature_collection, f)

    return bbox
Esempio n. 8
0
 def salvarLocalizacoes(self):
     prefixo = str(config['DEFAULT']['prefixo'])
     continuar = str(config['DEFAULT']['localizacoes']).upper()
     if (continuar=="SIM"):
         try:
             arquivo = open(HTML_DIR + prefixo + "geo.json",'w')
             arquivo.write(str(MultiPoint(self.__localizacoes)))
         except Exception as e:
             logging.error("SalvarLocalizacoes: " + str(e))
         finally:
             arquivo.close()
Esempio n. 9
0
    def test_dumps_multipoint3D(self):
        from chsdi.esrigeojsonencoder import dumps as esri_dumps
        from geojson import MultiPoint
        point = MultiPoint([(600000, 200000, 450), (650000, 250000, 650)],
                           properties={'name': 'toto'})

        result = esri_dumps(point)
        self.assertEqual(
            result,
            '{"spatialReference": {"wkid": 21781}, "points": [[600000, 200000, 450], [650000, 250000, 650]], "hasZ": true, "attributes": {"name": "toto"}}'
        )
Esempio n. 10
0
def convert_geocoded_entities_to_geojson(_geocoded_entities):
    data=[]
    for p in _geocoded_entities:
        # place={}
        # place["name"]=p[0]
        # place["count"]=p[1]
        # place["geo"]={ "name":p[2][0], "latitude":p[2][1][0], "longitude":p[2][1][1] }

        place = (p[2][1][1],p[2][1][0])
        data.append(place)
    print type( data)
    return MultiPoint(data)
Esempio n. 11
0
def geojson_output(limit=1):
    all_points = []
    with open('output_data.json', 'w') as file:
        map_data = pull_dob_data(limit)
        for each in map_data:
            if each.get('gis_latitude') and each.get('gis_longitude'):
                each_point = (float(each['gis_longitude']),
                              float(each['gis_latitude']))
                all_points.append(each_point)
        file.writelines(
            dumps(FeatureCollection([Feature(geometry=MultiPoint(all_points))
                                     ])))
Esempio n. 12
0
 def gen_point_dict(sp_filepath):
     with open(sp_filepath, mode='r', encoding='utf-8') as f:
         if TYPE == 'multipoint':
             coord = list()
             heights = list()
             cnt = 0
         while (True):
             line = f.readline()
             if not line:
                 break
             lat, lon, height = map(float, line.split()[:3])
             if TYPE == 'multipoint':
                 coord.append(
                     tuple(
                         transformer.transform(lat * 0.2 + 336000,
                                               lon * 0.2 + 6245250)))
                 heights.append(height * 0.2 + 20)
                 cnt += 1
                 if cnt == BLOCK:
                     d = OrderedDict()  # remember the inserting order
                     d['geometry'] = MultiPoint(coord)
                     d['height'] = heights
                     cnt = 0
                     coord.clear()
                     heights.clear()
                     yield d
             elif TYPE == 'point':
                 d = OrderedDict()
                 d['geometry'] = Point(
                     transformer.transform(lat * 0.2 + 336000,
                                           lon * 0.2 + 6245250))
                 d['height'] = height * 0.2 + 20
                 yield d
         if TYPE == 'multipoint':
             d = OrderedDict()  # remember the inserting order
             d['geometry'] = MultiPoint(coord)
             d['height'] = heights
             yield d
Esempio n. 13
0
def xyz2multipoint(inp, out, trans, block):
    """
	to geojson "Multipoint"
	"""
    jsonf = open(out, mode='w', encoding='utf-8')
    block = map(int, block)
    with open(inp, mode='r', encoding='utf-8') as f:
        coord = list()
        heights = list()
        cnt = 0
        while (True):
            line = f.readline().strip()
            if not line:
                break
            lat, lon, height = map(float, line.split()[:3])
            coord.append(
                tuple(trans.transform(lat * 0.2 + 336000,
                                      lon * 0.2 + 6245250)))
            heights.append(height * 0.2 + 20)
            cnt += 1
            if cnt == block:
                d = OrderedDict()  # remember the inserting order
                d['geometry'] = MultiPoint(coord)
                d['height'] = heights
                jsonf.write(json.dumps(d, sort_keys=False, indent=4))
                jsonf.write('\n')
                cnt = 0
                coord.clear()
                heights.clear()
        if coord:
            d = OrderedDict()  # remember the inserting order
            d['geometry'] = MultiPoint(coord)
            d['height'] = heights
            jsonf.write(json.dumps(d, sort_keys=False, indent=4))
            jsonf.write('\n')
    jsonf.close()
Esempio n. 14
0
def neighPatternHome():
    neighs = []
    neighborhoods = Neighborhood.query.all()
    for neigh in neighborhoods:
        if not neigh.name in neighs:
            neighs.append(neigh.name)

    households = Household.query.filter(Household.geom != None).all()
    points = []
    for hs in households:
        point = wkb.loads(str(hs.geom), hex=True)
        points.append((point.x, point.y))
    households = Feature(geometry=MultiPoint(points), id=1)
    return render_template('neighpattern.html',
                           ACCESS_KEY=MAPBOX_ACCESS_KEY,
                           neighs = neighs,
                           households=geojson.dumps(households)
                           )
Esempio n. 15
0
def clusteringPattern():
    neighs = []
    neighborhoods = Neighborhood.query.all()
    for neigh in neighborhoods:
        if not neigh.name in neighs:
            neighs.append(neigh.name)

    households = Household.query.filter(Household.geom != None).all()
    points = []
    for hs in households:
        point = wkb.loads(str(hs.geom), hex=True)
        points.append((point.x, point.y))
    households = Feature(geometry=MultiPoint(points), id=1)
    clusters, colors = getClusteredLayers()
    series = getClusteringPatterns(colors)
    return render_template('clusteringpattern.html',
                           ACCESS_KEY=MAPBOX_ACCESS_KEY,
                           neighs = neighs,
                           households=geojson.dumps(households),
                           clusters = geojson.dumps(clusters),
                           series = geojson.dumps(series)
                           )
Esempio n. 16
0
def create_geo_features():
    features = []
    conn = db_connect()
    cluster_centers = db_get_cluster_centers(conn)
    for c in cluster_centers:
        (label, count_photos, lat_deg, lon_deg) = c
        point = Point((lon_deg, lat_deg))
        get_geo_description(lat_deg, lon_deg)
        feature = Feature(geometry=point,
                          properties={
                              "photos-cluster-label": label,
                              "photos-cluster-count": count_photos,
                              "marker-color": "#c81e1e",
                              "marker-size": "large",
                              "marker-symbol": "camera"
                          })

        features.append(feature)

        polygon_coords = swap_lat_lon(db_get_hull_curve(conn, label))
        polygon = Polygon([polygon_coords])
        feature = Feature(geometry=polygon, properties={})

        features.append(feature)

    no_cluster_points = swap_lat_lon(db_get_no_cluster_points(conn))
    points = MultiPoint(no_cluster_points)
    feature = Feature(geometry=points,
                      properties={
                          "marker-color": "#f6ae13",
                          "marker-size": "small",
                          "marker-symbol": "camera"
                      })

    features.append(feature)

    conn.close()
    return features
Esempio n. 17
0
def nmea_file_to_points(filename):
    with open('test.nmea') as f:
        points = MultiPoint([lonlat(line) for line in f])
    return points
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###############################################################################
from geojson import Point
Point((-115.81, 37.24))
###############################################################################
from geojson import MultiPoint
MultiPoint([(-155.52, 19.61), (-156.22, 20.74), (-157.97, 21.46)])
###############################################################################
from geojson import LineString
LineString([(8.919, 44.4074), (8.923, 44.4075)])
###############################################################################
from geojson import MultiLineString
MultiLineString([[(3.75, 9.25), (-130.95, 1.52)],
                 [(23.15, -34.25), (-1.35, -4.65), (3.45, 77.95)]])
###############################################################################
from geojson import Polygon
Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
###############################################################################
Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)],
         [(-5.21, 23.51), (15.21, -10.81), (-20.51, 1.51), (-5.21, 23.51)]])
###############################################################################
from geojson import MultiPolygon
MultiPolygon([([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234),
                (3.78, 9.28)], ),
              ([(23.18, -34.29), (-1.31, -4.61), (3.41, 77.91),
                (23.18, -34.29)], )])
###############################################################################
from geojson import GeometryCollection, Point, LineString
from pprint import pprint
my_point = Point((23.532, -63.12))
Esempio n. 19
0
 def multipoint(self, count_limit=1000):
     """
     Returns a geojson mutipoint object with a random number of random points
     """
     return MultiPoint(
         [self.lnglat() for i in range(randint(0, count_limit))])
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###############################################################################
from geojson import Point
Point((-115.81, 37.24))  # doctest: +ELLIPSIS
###############################################################################
from geojson import MultiPoint
MultiPoint([(-155.52, 19.61), (-156.22, 20.74),
            (-157.97, 21.46)])  # doctest: +ELLIPSIS
###############################################################################
from geojson import LineString
LineString([(8.919, 44.4074), (8.923, 44.4075)])  # doctest: +ELLIPSIS
###############################################################################
from geojson import MultiLineString
MultiLineString([[(3.75, 9.25), (-130.95, 1.52)],
                 [(23.15, -34.25), (-1.35, -4.65), (3.45, 77.95)]])
###############################################################################
from geojson import Polygon
Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
###############################################################################
Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)],
         [(-5.21, 23.51), (15.21, -10.81), (-20.51, 1.51), (-5.21, 23.51)]])
###############################################################################
from geojson import MultiPolygon
MultiPolygon([([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234),
                (3.78, 9.28)], ),
              ([(23.18, -34.29), (-1.31, -4.61), (3.41, 77.91),
                (23.18, -34.29)], )])
###############################################################################
from geojson import GeometryCollection, Point, LineString
from pprint import pprint
Esempio n. 21
0
def compare_osm_kenyaopendata():
    osm = geojson.loads(readfile('nairobi-schools-osm.geojson'))
    kod = geojson.loads(readfile('kibera-primary-secondary-schools.geojson'))
    result = {}
    result['type'] = 'FeatureCollection'
    result['features'] = []
    kibera = deepcopy(result)
    mathare = deepcopy(result)

    #TODO make sure all features in KOD are in OSM (through osmly)
    for feature in osm.features:
        points = [(feature.geometry.coordinates[0],
                   feature.geometry.coordinates[1])]

        if 'osm:official_name' in feature.properties:
            found_match = False
            for kod_feature in kod.features:
                if 'official_name' in kod_feature.properties and kod_feature.properties[
                        'official_name'] == feature.properties[
                            'osm:official_name']:
                    #print feature.properties['official_name']
                    found_match = True
                    points.append((kod_feature.geometry.coordinates[0],
                                   kod_feature.geometry.coordinates[1]))
                    for kod_property in kod_feature.properties.keys():
                        if kod_property != 'lat' and kod_property != 'lon':
                            feature.properties[
                                "kenyaopendata:" +
                                kod_property] = kod_feature.properties[
                                    kod_property]

            if found_match == False:
                print "WARN: OSM official_name has no match: " + feature.properties[
                    'osm:name'] + ", " + feature.properties[
                        'osm:official_name'] + ", " + feature['id']

        geom = MultiPoint(points)
        result['features'].append({
            "type": "Feature",
            "properties": feature.properties,
            "geometry": geom
        })
        if feature.properties['osm:location'] == 'kibera':
            kibera['features'].append({
                "type": "Feature",
                "properties": feature.properties,
                "geometry": geom
            })
        else:
            mathare['features'].append({
                "type": "Feature",
                "properties": feature.properties,
                "geometry": geom
            })

    dump = geojson.dumps(result, sort_keys=True, indent=2)
    writefile('nairobi-combined-schools.geojson', dump)
    dump = geojson.dumps(kibera, sort_keys=True, indent=2)
    writefile('kibera-schools.geojson', dump)
    dump = geojson.dumps(mathare, sort_keys=True, indent=2)
    writefile('mathare-schools.geojson', dump)
Esempio n. 22
0
def get_geo_tag_as_geojson(_tweets):
    geotag=[ (float(t["geo"][6:-1].split(" ")[0]),float(t["geo"][6:-1].split(" ")[1])) for t in _tweets if t["geo"] !=""]
    # print type(geotag)
    return MultiPoint(geotag)
Esempio n. 23
0
from geojson import Point

point = Point((126.97689056396484, 37.57880031671566))
print(point)
print(point.is_valid)

from geojson import MultiPoint

multi_p = MultiPoint([(126.97689056396484, 37.57880031671566),
                      (126.97079658508302, 37.55492071859406)])
print(multi_p)
print(multi_p.is_valid)

from geojson import LineString

list_str = LineString([(126.95972442626953, 37.575671232633184),
                       (126.99354171752928, 37.57607938149231)])
print(list_str)
print(list_str.is_valid)

from geojson import MultiLineString

multi_str = MultiLineString([((126.95972442626953, 37.575671232633184),
                              (126.99354171752928, 37.57607938149231)),
                             [(126.95972442626953, 37.575671232633184),
                              (126.99354171752928, 37.57607938149231)]])
print(multi_str)
print(multi_str.is_valid)

from geojson import Polygon
Esempio n. 24
0
        # for cord in list(cords_set):
        #     cord_tuple = tuple(cord)
        #     if len(cord_id[cord_tuple]) != 1:
        #         text = process_text(cord_id[cord_tuple])
        #     else:
        #         doc = cluster_db[cord_id[cord_tuple][0]]
        #         if "twitter" in doc:
        #             text = "Twitter: " + doc['text']
        #         elif "instagram" in doc:
        #             text = "Instagram: " + doc['text']
        #     cord_p = Point(cord)
        #     if i == 0:
        #         feature = Feature(geometry=cord_p, properties={"color": "#826969", "text": text})
        #     else:
        #         feature = Feature(geometry=cord_p, properties={"color": color_lst[i-1], "text": text})
        #     features.append(feature)
        cord_mp = MultiPoint(list(cords_set))
        if i == 0:
            feature = Feature(geometry=cord_mp,
                              properties={"color": "#826969"})
        else:
            feature = Feature(geometry=cord_mp,
                              properties={
                                  "color": color_lst[i - 1],
                                  "summary": summary
                              })
        features.append(feature)
feature_collection = FeatureCollection(features)
with open('train_cluster.geojson', 'w') as outfile:
    geojson.dump(feature_collection, outfile)
Esempio n. 25
0
# plot(data1)

# Generate geojson for MapMatching - QGIS
trajectories = summary(df)

for trj_id, cnt in trajectories.items():

    if path.exists("mapmatched/{}.geojson".format(trj_id)):
        continue

    data = df[df["trj_id"] == trj_id]
    trj_coordinate[trj_id] = list(zip(data["rawlng"], data["rawlat"]))
    # start, end = data['realtime'].values[0].__str__(), data['realtime'].values[-1].__str__()
    start, end = str(data['realtime'].iloc[0]), str(data['realtime'].iloc[-1])
    coord = trj_coordinate[trj_id]
    geometry = MultiPoint(coord)

    if mapmatch_enable:
        geometry, distance = map_matching(geometry['coordinates'])

    crs = {"type": "trajectory", "properties": {"name": "EPSG:4326"}}
    prop = {
        "country": "Singapore",
        "trj_id": trj_id,
        "distance": distance,
        "origin_time": start,
        "destination_time": end
    }

    # geometryJSON.append(Feature(geometry = geometry, properties = {"country": "Singapore"}))
    geometryJSON = Feature(geometry=geometry, properties=prop)