Python geopy.Point() Examples

The following are 23 code examples of geopy.Point(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module geopy , or try the search function .
Example #1
Source File: utils.py    From YAFS with MIT License 6 votes vote down vote up
def getCoordinates(start_point, end_point, distance_meters):
    """
    Calculates the new coordinates between two points depending
    of the specified distance and the calculated bearing.

    Parameters
    ----------
    start_point: geopy.Point
    end_point: geopy.Point
    distance_meters: float

    Returns
    -------
    point: geopy.Point
        A new point between the start and the end points.
    """
    warnings.warn("The getCoordinates function is deprecated and "
                  "will be removed in version 2.0.0. "
                  "Use the get_coordinates function instead.",
                  FutureWarning,
                  stacklevel=8
                  )
    return get_coordinates(start_point, end_point, distance_meters) 
Example #2
Source File: utils.py    From YAFS with MIT License 6 votes vote down vote up
def get_coordinates(start_point, end_point, distance_meters):
    """
    Calculates the new coordinates between two points depending
    of the specified distance and the calculated bearing.

    Parameters
    ----------
    start_point: geopy.Point
    end_point: geopy.Point
    distance_meters: float

    Returns
    -------
    point: geopy.Point
        A new point between the start and the end points.
    """
    bearing = get_bearing(start_point, end_point)

    distance_km = distance_meters / 1000
    d = geo_dist.VincentyDistance(kilometers=distance_km)
    destination = d.destination(point=start_point, bearing=bearing)

    return geopy.Point(destination.latitude, destination.longitude) 
Example #3
Source File: utils.py    From YAFS with MIT License 6 votes vote down vote up
def getPointInTheMiddle(start_point, end_point, time_diff, point_idx):
    """
    Calculates a new point between two points depending of the
    time difference between them and the point index.

    Parameters
    ----------
    start_point: DataFrame
    end_point: DataFrame
    time_diff: float
    point_idx: int
        Point index between the start and the end points

    Returns
    -------
    point: list
        A new point between the start and the end points.
    """
    warnings.warn("The getPointInTheMiddle function is deprecated and "
                  "will be removed in version 2.0.0. "
                  "Use the get_point_in_the_middle function instead.",
                  FutureWarning,
                  stacklevel=8
                  )
    return get_point_in_the_middle(start_point, end_point, time_diff, point_idx) 
Example #4
Source File: google.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def parse_json(self, page, exactly_one=True):
        if not isinstance(page, basestring):
            page = util.decode_page(page)
        doc = json.loads(page)
        places = doc.get('Placemark', [])

        if len(places) == 0:
            # Got empty result. Parse out the status code and raise an error if necessary.
            status = doc.get("Status", [])
            status_code = status["code"]
            self.check_status_code(status_code)
            return None
        elif exactly_one and len(places) != 1:
            raise ValueError("Didn't find exactly one placemark! " \
                             "(Found %d.)" % len(places))

        def parse_place(place):
            location = place.get('address')
            longitude, latitude = place['Point']['coordinates'][:2]
            return (location, (latitude, longitude))
        
        if exactly_one:
            return parse_place(places[0])
        else:
            return [parse_place(place) for place in places] 
Example #5
Source File: rdf.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def find(self, document):
        if isinstance(document, basestring):
            document = ElementTree.fromstring(document)
        elif not ElementTree.iselement(document):
            document = ElementTree.parse(document)
        
        point_qname = self._get_qname(self.POINT_CLASS)
        lat_qname = self._get_qname(self.LATITUDE_PROPERTY)
        long_qname = self._get_qname(self.LONGITUDE_PROPERTY)
        alt_qname = self._get_qname(self.ALTITUDE_PROPERTY)
        
        queue = [document]
        while queue:
            element = queue.pop()
            if not self.point_class or element.tag == point_qname:
                lat_el = element.find(lat_qname)
                long_el = element.find(long_qname)
                alt_el = element.find(alt_qname)
                if lat_el is not None and long_el is not None:
                    latitude = lat_el.text
                    longitude = long_el.text
                    altitude = alt_el and alt_el.text
                    try:
                        point = Point((latitude, longitude, altitude))
                    except (TypeError, ValueError):
                        if not self.ignore_invalid:
                            raise
                    else:
                        yield Location(None, point)
                
                queue.extend(reversed(element)) 
Example #6
Source File: geo.py    From Ocean-Data-Map-Project with GNU General Public License v3.0 5 votes vote down vote up
def points_between(start, end, numpoints, constantvalue=False):
    distance = []
    latitude = []
    longitude = []

    lat0 = start.latitude
    lon0 = start.longitude
    lat1 = end.latitude
    lon1 = end.longitude

    if constantvalue and np.isclose(lat0, lat1):
        latitude = np.ones(numpoints) * lat0
        longitude = np.linspace(lon0, lon1, num=numpoints)
        for lon in longitude:
            distance.append(vincenty(start, geopy.Point(lat0, lon)).km)
        if lon1 > lon0:
            b = 90
        else:
            b = -90
    elif constantvalue and np.isclose(lon0, lon1):
        latitude = np.linspace(lat0, lat1, num=numpoints)
        longitude = np.ones(numpoints) * lon0
        for lat in latitude:
            distance.append(vincenty(start, geopy.Point(lat, lon0)).km)
        if lat1 > lat0:
            b = 0
        else:
            b = 180
    else:
        total_distance = vincenty(start, end).km
        distance = np.linspace(0, total_distance, num=numpoints)
        b = bearing(lat0, lon0, lat1, lon1)

        for d in distance:
            p = VincentyDistance().destination(start, b, d)
            latitude.append(p.latitude)
            longitude.append(p.longitude)

    return list(map(np.array, [distance, latitude, longitude, b])) 
Example #7
Source File: line.py    From Ocean-Data-Map-Project with GNU General Public License v3.0 5 votes vote down vote up
def parse_query(self, query):
        super(LinePlotter, self).parse_query(query)

        points = query.get('path')
        if points is None or len(points) == 0:
            points = [
                '47 N 52.8317 W',
                '47 N 42 W'
            ]

        self.points = points

        surface = query.get('surfacevariable')
        if surface is not None and (surface == '' or surface == 'none'):
            surface = None

        self.surface = surface

        name = query.get('name')
        if name is None or name == '':
            p0 = geopy.Point(points[0])
            p1 = geopy.Point(points[-1])
            name = gettext("(%0.4f N, %0.4f W) to (%0.4f N, %0.4f W)") % (
                p0.latitude, p0.longitude,
                p1.latitude, p1.longitude,
            )

        self.name = name 
Example #8
Source File: grid.py    From Ocean-Data-Map-Project with GNU General Public License v3.0 5 votes vote down vote up
def _path_to_points(points, n, intimes=None):
    if intimes is None:
        intimes = [0] * len(points)

    tuples = list(zip(points, points[1::], intimes, intimes[1::]))

    d = VincentyDistance()
    dist_between_pts = []
    for pair in tuples:
        dist_between_pts.append(d.measure(pair[0], pair[1]))

    total_distance = np.sum(dist_between_pts)
    distances = []
    target_lat = []
    target_lon = []
    bearings = []
    times = []
    for idx, tup in enumerate(tuples):
        npts = int(np.ceil(n * (dist_between_pts[idx] /
                                total_distance)))
        if npts < 2:
            npts = 2
        p0 = geopy.Point(tup[0])
        p1 = geopy.Point(tup[1])

        p_dist, p_lat, p_lon, b = points_between(p0, p1, npts)
        if len(distances) > 0:
            distances.extend(np.add(p_dist, distances[-1]))
        else:
            distances.extend(p_dist)
        target_lat.extend(p_lat)
        target_lon.extend(p_lon)
        bearings.extend([b] * len(p_dist))
        times.extend([tup[2] + i * (tup[3] - tup[2]) / (npts - 1)
                     for i in range(0, npts)])

    return distances, times, target_lat, target_lon, bearings 
Example #9
Source File: node.py    From OSMDeepOD with MIT License 5 votes vote down vote up
def to_geojson(self):
        return json.dumps({"type": "Point", "coordinates": [self.latitude, self.longitude]}) 
Example #10
Source File: node.py    From OSMDeepOD with MIT License 5 votes vote down vote up
def __init__(self, lat=0.0, lon=0.0, osm_id=0):
        super(Node, self).__new__(Point, latitude=lat, longitude=lon)
        self.osm_id = osm_id 
Example #11
Source File: test_get_circle_centers.py    From populartimes with MIT License 5 votes vote down vote up
def test_get_circle_centers():
    # test if circles fully cover the rect
    for sw, ne, w, h, r, circles in generate_testcases():
        # test with 1000 random points
        for tst in range(1000):
            # choose random point within rect
            p = (random.uniform(0,w), random.uniform(0,h))
            # translate to lat/lng
            pp = VincentyDistance(meters=p[0]).destination(
                VincentyDistance(meters=p[1])
                .destination(point=sw, bearing=90),
                bearing=0
            )
            # check if point is contained in any of the calculated circles
            assert any([vincenty(pp, Point(c[0], c[1])).meters <= r for c in circles]) 
Example #12
Source File: crawler.py    From populartimes with MIT License 5 votes vote down vote up
def get_circle_centers(b1, b2, radius):
    """
    the function covers the area within the bounds with circles

    :param b1: south-west bounds [lat, lng]
    :param b2: north-east bounds [lat, lng]
    :param radius: specified radius, adapt for high density areas
    :return: list of circle centers that cover the area between lower/upper
    """

    sw = Point(b1)
    ne = Point(b2)

    # north/east distances
    dist_lat = vincenty(Point(sw[0], sw[1]), Point(ne[0], sw[1])).meters
    dist_lng = vincenty(Point(sw[0], sw[1]), Point(sw[0], ne[1])).meters

    circles = cover_rect_with_cicles(dist_lat, dist_lng, radius)
    cords = [
        VincentyDistance(meters=c[0])
        .destination(
            VincentyDistance(meters=c[1])
            .destination(point=sw, bearing=90),
            bearing=0
        )[:2]
        for c in circles
    ]

    return cords 
Example #13
Source File: gpx.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _parse_waypoint(self, element):
        waypoint = {}
        point = Point(element.get('lat'), element.get('lon')) 
Example #14
Source File: html.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _get_location(self, attrs):
        position = attrs.pop('position')
        name = attrs.pop('placename')
        if position is not None:
            if position or not self.ignore_invalid:
                try:
                    point = Point(position)
                except (TypeError, ValueError):
                    if not self.ignore_invalid:
                        raise
                else:
                    return Location(name, point, attrs) 
Example #15
Source File: utils.py    From YAFS with MIT License 5 votes vote down vote up
def getBearing(start_point, end_point):
    """
    Calculates the bearing between two points.

    Parameters
    ----------
    start_point: geopy.Point
    end_point: geopy.Point

    Returns
    -------
    point: int
        Bearing in degrees between the start and end points.
    """
    warnings.warn("The getBearing function is deprecated and "
                  "will be removed in version 2.0.0. "
                  "Use the get_bearing function instead.",
                  FutureWarning,
                  stacklevel=8
                  )
    return get_bearing(start_point, end_point) 
Example #16
Source File: yahoo.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def parse_json(self, page, exactly_one=True):
        if not isinstance(page, basestring):
            page = util.decode_page(page)
        doc = json.loads(page)
        results = doc.get('ResultSet', []).get('Results', [])

        if not results:
            raise ValueError("No results found")
        elif exactly_one and len(results) != 1:
            raise ValueError("Didn't find exactly one placemark! " \
                             "(Found %d.)" % len(results))

        def parse_result(place):
            line1, line2, line3, line4 = place.get('line1'), place.get('line2'), place.get('line3'), place.get('line4')
            address = util.join_filter(", ", [line1, line2, line3, line4])
            city = place.get('city')
            state = place.get('state')
            country = place.get('country')
            location = util.join_filter(", ", [address, city, country])
            lat, lng = place.get('latitude'), place.get('longitude')
            #if lat and lng:
            #    point = Point(floatlat, lng)
            #else:
            #    point = None
            return (location, (float(lat), float(lng)))
    
        if exactly_one:
            return parse_result(results[0])
        else:
            return [parse_result(result) for result in results] 
Example #17
Source File: geohash.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def encode(self, *args, **kwargs):
        precision = kwargs.pop('precision', self.precision)
        point = Point(*args, **kwargs)
        lat_min, latitude, lat_max = -90, 0, 90
        long_min, longitude, long_max = -180, 0, 180
        string = ''
        bytes = []
        odd_bit = False
        for i in xrange(precision):
            byte = 0
            for bit in (16, 8, 4, 2, 1):
                if odd_bit:
                    if point.latitude >= latitude:
                        byte |= bit
                        lat_min = latitude
                    else:
                        lat_max = latitude
                    latitude = (lat_min + lat_max) / 2.
                else:
                    if point.longitude >= longitude:
                        byte |= bit
                        long_min = longitude
                    else:
                        long_max = longitude
                    longitude = (long_min + long_max) / 2.
                odd_bit = not odd_bit
            bytes.append(byte) 
        return ''.join([self.ENCODE_MAP[byte] for byte in bytes]) 
Example #18
Source File: geohash.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, point_class=Point, precision=12):
        self.point_class = point_class
        self.precision = precision 
Example #19
Source File: polyline_generator.py    From PokemonGo-Bot-Backup with MIT License 5 votes vote down vote up
def get_pos(self):
        if self.speed > self.get_total_distance():
            self._last_pos = self.destination
            self._last_step = len(self._step_keys)-1
        if self.get_last_pos() == self.destination:
            return self.get_last_pos()
        distance = self.speed
        origin = Point(*self._last_pos)
        ((so_lat, so_lng), (sd_lat, sd_lng)) = self._step_dict[self._step_keys[self._last_step]]
        bearing = self._calc_bearing(so_lat, so_lng, sd_lat, sd_lng)
        while haversine.haversine(self._last_pos, (sd_lat, sd_lng))*1000 < distance:
            distance -= haversine.haversine(self._last_pos, (sd_lat, sd_lng))*1000
            self._last_pos = (sd_lat, sd_lng)
            if self._last_step < len(self._step_keys)-1:
                self._last_step += 1
                ((so_lat, so_lng), (sd_lat, sd_lng)) = self._step_dict[self._step_keys[self._last_step]]
                bearing = self._calc_bearing(so_lat, so_lng, sd_lat, sd_lng)
                origin = Point(so_lat, so_lng)
                lat, lng = self._calc_next_pos(origin, distance, bearing)
                if haversine.haversine(self._last_pos, (lat, lng))*1000 < distance:
                    distance -= haversine.haversine(self._last_pos, (lat, lng))*1000
                    self._last_pos = (lat, lng)
            else:
                return self.get_last_pos()
        else:
            lat, lng = self._calc_next_pos(origin, distance, bearing)
            self._last_pos = (lat, lng)
            return self.get_last_pos() 
Example #20
Source File: step_walker.py    From PokemonGo-Bot-Backup with MIT License 5 votes vote down vote up
def _get_next_pos(self, lat, lon, bearing, speed, precision):
        origin = Point(lat, lon)
        if speed == 0.0:
            return lat, lon
        if speed == float("inf"):
            return self.destLat, self.destLng
        else:
            offset_angle = (1/self.speed)*(precision/1.74)
            lat, lon, _ = VincentyDistance(kilometers=speed*1e-3).destination(origin, bearing + uniform(-offset_angle, offset_angle))
            return lat, lon 
Example #21
Source File: utils.py    From YAFS with MIT License 5 votes vote down vote up
def get_bearing(start_point, end_point):
    """
    Calculates the bearing between two points.

    Parameters
    ----------
    start_point: geopy.Point
    end_point: geopy.Point

    Returns
    -------
    point: int
        Bearing in degrees between the start and end points.
    """
    start_lat = math.radians(start_point.latitude)
    start_lng = math.radians(start_point.longitude)
    end_lat = math.radians(end_point.latitude)
    end_lng = math.radians(end_point.longitude)

    d_lng = end_lng - start_lng
    if abs(d_lng) > math.pi:
        if d_lng > 0.0:
            d_lng = -(2.0 * math.pi - d_lng)
        else:
            d_lng = (2.0 * math.pi + d_lng)

    tan_start = math.tan(start_lat / 2.0 + math.pi / 4.0)
    tan_end = math.tan(end_lat / 2.0 + math.pi / 4.0)
    d_phi = math.log(tan_end / tan_start)
    bearing = (math.degrees(math.atan2(d_lng, d_phi)) + 360.0) % 360.0

    return bearing 
Example #22
Source File: grid.py    From Ocean-Data-Map-Project with GNU General Public License v3.0 4 votes vote down vote up
def points_between(start, end, numpoints):
    distance = VincentyDistance()

    distances = []
    latitudes = []
    longitudes = []

    lat0 = start.latitude
    lon0 = start.longitude
    lat1 = end.latitude
    lon1 = end.longitude

    if np.isclose(lat0, lat1):
        # Constant latitude
        latitudes = np.ones(numpoints) * lat0
        longitudes = np.linspace(lon0, lon1, num=numpoints)
        for lon in longitudes:
            distances.append(distance.measure(start, geopy.Point(lat0, lon)))
        if lon1 > lon0:
            b = 90
        else:
            b = -90
    elif np.isclose(lon0, lon1):
        # Constant longitude
        latitudes = np.linspace(lat0, lat1, num=numpoints)
        longitudes = np.ones(numpoints) * lon0
        for lat in latitudes:
            distances.append(distance.measure(start, geopy.Point(lat, lon0)))
        if lat1 > lat0:
            b = 0
        else:
            b = 180
    else:
        # Great Circle
        total_distance = distance.measure(start, end)
        distances = np.linspace(0, total_distance, num=numpoints)
        b = bearing(lat0, lon0, lat1, lon1)

        for d in distances:
            p = distance.destination(start, b, d)
            latitudes.append(p.latitude)
            longitudes.append(p.longitude)

    return distances, latitudes, longitudes, b 
Example #23
Source File: geo.py    From Ocean-Data-Map-Project with GNU General Public License v3.0 4 votes vote down vote up
def path_to_points(points, n=100, times=None):
    if times is None:
        times = [0] * len(points)

    if len(times) != len(points):
        if isinstance(times[0], datetime.datetime):
            times = times[0] + np.array([datetime.timedelta(0, d) for d in np.linspace(
                    0, (times[-1] - times[0]).total_seconds(), num=len(points))])
        else:
            times = np.linspace(times[0], times[-1], num=len(points))

    tuples = list(zip(points, points[1:], times, times[1:]))

    distance_between = []
    for pair in tuples:
        distance_between.append(vincenty(pair[0], pair[1]).km)

    total_distance = np.sum(distance_between)
    distance = []
    latitude = []
    longitude = []
    bearings = []
    output_time = []

    for index, pair in enumerate(tuples):
        n_pts = int(np.ceil(n * (distance_between[index] /
                                 total_distance)))
        n_pts = np.clip(n_pts, 2, n)
        p = list(map(geopy.Point, pair[0:2]))

        p_dist, p_lat, p_lon, b = points_between(p[0], p[1], n_pts)
        if len(distance) > 0:
            distance.extend(np.add(p_dist, distance[-1]))
        else:
            distance.extend(p_dist)

        latitude.extend(p_lat)
        longitude.extend(p_lon)
        bearings.extend([b] * len(p_dist))
        output_time.extend([
            pair[2] + i * (pair[3] - pair[2]) / (n_pts - 1)
            for i in range(0, n_pts)
        ])
    return distance, output_time, latitude, longitude, bearings