Looks up lat/lon info with goole given a list
    of positions as parsed by parsePositionFile.
    Returns google results in form of dicionary
540925
def lookupGeoInfo(positions):
    
    list_data=[]
    oldlat=0
    oldlon=0
    d={}
    for pos in positions:
        # Only lookup point if it is above threshold
        diff_lat=abs(float(pos['lat'])-oldlat)
        diff_lon=abs(float(pos['lon'])-oldlon)
        if (diff_lat>POS_THRESHOLD_DEG) or\
           (diff_lon>POS_THRESHOLD_DEG):
            d=lookup_by_latlon(pos['lat'],pos['lon'])
            oldlat=float(pos['lat'])
            oldlon=float(pos['lon'])
        else:
            logger.debug("Skipping %s/%s, close to prev"%(pos['lat'],pos['lon']))

        # Use fresh lookup value or old value
        list_data.append(d)

    logger.info('looked up %d positions'%(len(list_data)))
    return list_data
421691
def _get_lat_lon_indices(lsm_lat_array, lsm_lon_array, lat, lon):
    
    if lsm_lat_array.ndim == 2 and lsm_lon_array.ndim == 2:
        lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = \
            np.where((lsm_lat_array == lat))
        lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = \
            np.where((lsm_lon_array == lon))

        index_lsm_grid_lat = np.intersect1d(lsm_lat_indices_from_lat,
                                            lsm_lat_indices_from_lon)[0]
        index_lsm_grid_lon = np.intersect1d(lsm_lon_indices_from_lat,
                                            lsm_lon_indices_from_lon)[0]

    elif lsm_lat_array.ndim == 1 and lsm_lon_array.ndim == 1:
        index_lsm_grid_lon = np.where(lsm_lon_array == lon)[0][0]
        index_lsm_grid_lat = np.where(lsm_lat_array == lat)[0][0]
    else:
        raise IndexError("Lat/Lon lists have invalid dimensions. "
                         "Only 1D or 2D arrays allowed ...")

    return index_lsm_grid_lat, index_lsm_grid_lon
834283
def get_locations_from_coords(self, longitude, latitude, levels=None):
        
        resp = requests.get(SETTINGS['url'] + '/point/4326/%s,%s?generation=%s' % (longitude, latitude, SETTINGS['generation']))
        resp.raise_for_status()

        geos = []
        for feature in resp.json().itervalues():
            try:
                geo = self.get_geography(feature['codes']['MDB'],
                                         feature['type_name'].lower())

                if not levels or geo.geo_level in levels:
                    geos.append(geo)
            except LocationNotFound as e:
                log.warn("Couldn't find geo that Mapit gave us: %s" % feature, exc_info=e)

        return geos
557618
def strings(self):
        
        return [
            toString(self.lat, LAT),
            toString(self.lon, LON)
        ]
845705
def localortho(lon, lat):
    
    local_srs = osr.SpatialReference()
    local_proj = '+proj=ortho +lat_0=%0.7f +lon_0=%0.7f +datum=WGS84 +units=m +no_defs ' % (lat, lon)
    local_srs.ImportFromProj4(local_proj)
    return local_srs
67887
def location (self, pos):
    
    result = ''
    if self.filename:
      result += self.filename + ':'
    if pos:
      result += str(pos)
    return result
202031
def parse_location(location):
    
    def split_dms(text, hemisphere):
        """Split degrees, minutes and seconds string.

        Args:
            text (str): Text to split

        Returns::
            float: Decimal degrees
        """
        out = []
        sect = []
        for i in text:
            if i.isdigit():
                sect.append(i)
            else:
                out.append(sect)
                sect = []
        d, m, s = [float(''.join(i)) for i in out]
        if hemisphere in 'SW':
            d, m, s = [-1 * x for x in (d, m, s)]
        return to_dd(d, m, s)

    for sep in ';, ':
        chunks = location.split(sep)
        if len(chunks) == 2:
            if chunks[0].endswith('N'):
                latitude = float(chunks[0][:-1])
            elif chunks[0].endswith('S'):
                latitude = -1 * float(chunks[0][:-1])
            else:
                latitude = float(chunks[0])
            if chunks[1].endswith('E'):
                longitude = float(chunks[1][:-1])
            elif chunks[1].endswith('W'):
                longitude = -1 * float(chunks[1][:-1])
            else:
                longitude = float(chunks[1])
            return latitude, longitude
        elif len(chunks) == 4:
            if chunks[0].endswith(('s', '"')):
                latitude = split_dms(chunks[0], chunks[1])
            else:
                latitude = float(chunks[0])
                if chunks[1] == 'S':
                    latitude = -1 * latitude
            if chunks[2].endswith(('s', '"')):
                longitude = split_dms(chunks[2], chunks[3])
            else:
                longitude = float(chunks[2])
                if chunks[3] == 'W':
                    longitude = -1 * longitude
            return latitude, longitude
83906
def get(self, pos):
        """"""
        latitude = int(round(pos['latitude']))
        search_set = self.bins[latitude]
        i = 1
        if latitude - i >= -90:
            search_set += self.bins[latitude-i]
        if latitude + i <= 90:
            search_set += self.bins[latitude+i]
        while len(search_set) == 0 and i <= 200:
            if latitude - i >= -90:
                search_set += self.bins[latitude-i]
            if latitude + i <= 90:
                search_set += self.bins[latitude+i]
            i += 1
        return find_closest(search_set, pos)
360249
def get_locations(self, filter_to_my_group=False):
        """"""
        resp = self._post('general-retrievelocations', 'locations')
        groups = {}
        if resp['groupinfo']:
            for group in resp['groupinfo']:
                groups[group['id']] = Group(
                                            name=group.get('name'),
                                            inventory_id=group.get('id')
                                            )
        final_resp = []
        if resp['data']:
            if filter_to_my_group:
                resp['data'] = {self.groupid: resp['data'][self.groupid]}
            for groupid, sublocation in resp['data'].items():
                if type(sublocation) is dict:
                    sublocation = [loc for _, loc in sublocation.items()]
                    sublocation = flatten_list(sublocation)
                if type(sublocation) is list:
                    sublocation = flatten_list(sublocation)
                for location in sublocation:
                    group = groups[groupid]
                    final_resp.append(Location(
                                            name=location.get('name'),
                                            inventory_id=location.get('id'),
                                            parent=location.get('parent'),
                                            group=group,
                                            barcode=location.get('barcode')
                                      ))
        return final_resp
473607
def get_location(query, format, api_key):
    """"""

    # Play nice with the API...
    sleep(1)
    geolocator = OpenCage(api_key=api_key, timeout=10)

    # Variables for storing the data
    data = {"city": None,
            "address_1": None,
            "postal_code": None,
            "country": None,
            "county": None,
            "state": None,
            "country_code": None,
            "latitude": None,
            "longitude": None,
            "continent": None}
    road = ""
    number = ""
    # Default None values
    location_data = {"city": None,
                     "road": None,
                     "house_number": None,
                     "postcode": None,
                     "country": None,
                     "county": None,
                     "state": None,
                     "ISO_3166-1_alpha-2": None,
                     "country_code": None,
                     "lat": None,
                     "lng": None}

    # Reverse geocoding ... from coordinates to address
    if format == "reverse":
        # If the query (coordinates) is not empty
        if query is None or len(query) < 3:
            pass
        else:
            location = geolocator.reverse(query)
            if location is not None:
                location_data = location[0].raw[u'components']
                location_data["lat"] = location[0].raw[u'geometry']["lat"]
                location_data["lng"] = location[0].raw[u'geometry']["lng"]
    # Direct geocoding ... from address to coordinates and full address
    if format == "direct":
        # If the query (address) is not empty
        if query is None or len(query) < 3:
            pass
        else:
            location = geolocator.geocode(query)
            if location is not None:
                location_data = location.raw[u'components']
                location_data["lat"] = location.raw[u'geometry']["lat"]
                location_data["lng"] = location.raw[u'geometry']["lng"]

    # Extract the meaningful data
    for component in location_data:
        if component == "town" or component == "city":
            data["city"] = location_data[component]
        if component == "road":
            road = location_data[component]
        if component == "house_number":
            number = location_data[component]
        if component == "postcode":
            data["postal_code"] = location_data[component]
        if component == "country":
            data["country"] = location_data[component]
        if component == "county":
            data["county"] = location_data[component]
        if component == "state":
            data["state"] = location_data[component]
        if component == "ISO_3166-1_alpha-2":
            data["country_code"] = location_data[component]
    # The address need to be reconstructed
    data["address_1"] = unicode(road) + " " + unicode(number)
    data["latitude"] = location_data["lat"]
    data["longitude"] = location_data["lng"]
    # Format the country code to three letters
    try:
        country_data = transformations.cca2_to_ccn(data["country_code"])
        data["country_code"] = transformations.ccn_to_cca3(country_data)
    except:
        data["country_code"] = None
    # Get the continent
    try:
        country_data = transformations.cc_to_cn(data["country_code"])
        data["continent"] = transformations.cn_to_ctn(country_data)
    except:
        data["continent"] = None

    # Return the final data
    return data
561962
def find_near(lat, lon, *, n=10, session=None):
    """"""
    search_params = {'npoints': n, 'clat': lat, 'clon': lon, 
                     'Columns[]': ['Subregion', 'Notes', 'CollectionYear', 
                                   'ReservoirAge', 'ReservoirErr', 'C14age', 
                                   'C14err', 'LabID', 'Delta13C', 'nextime', 
                                   'Genus', 'Species', 'Feeding', 'Name']}
    resp = _query_near(session=session, **search_params)
    df = _response_to_dataframe(resp)
    df_clean = _clean_dataframe(df)
    return df_clean
723553
def __geo_point(lat, lon, elev):
        
        logger_noaa_lpd.info("enter geo_point")
        coordinates = []
        geo_dict = OrderedDict()
        geometry_dict = OrderedDict()
        for index, point in enumerate(lat):
            coordinates.append(lat[index])
            coordinates.append(lon[index])
        if elev:
            coordinates = coordinates + elev
        geometry_dict['type'] = 'Point'
        geometry_dict['coordinates'] = coordinates
        geo_dict['type'] = 'Feature'
        geo_dict['geometry'] = geometry_dict
        return geo_dict
606822
def get_latlon(self, use_cached=True):
        """"""
        device_json = self.get_device_json(use_cached)
        lat = device_json.get("dpMapLat")
        lon = device_json.get("dpMapLong")
        return (float(lat) if lat else None,
                float(lon) if lon else None, )
98025
def _parse_json(self, page, exactly_one=True):
        ''''''

        places = page.get('results', [])
        if not len(places):
            self._check_status(page.get('status'))
            return None

        def parse_place(place):
            '''Get the location, lat, lng from a single json place.'''
            location = place.get('formatted_address')
            latitude = place['geometry']['location']['lat']
            longitude = place['geometry']['location']['lng']
            return Location(location, (latitude, longitude), place)

        if exactly_one:
            return parse_place(places[0])
        else:
            return [parse_place(place) for place in places]
50979
def resolved_row(objs, geomatcher):
    """"""
    def get_locations(lst):
        for elem in lst:
            try:
                yield elem['location']
            except TypeError:
                yield elem

    geomatcher['RoW'] = geomatcher.faces.difference(
        reduce(
            set.union,
            [geomatcher[obj] for obj in get_locations(objs)]
        )
    )
    yield geomatcher
    del geomatcher['RoW']
1170102
def coords_callback(self, data):
        
        for node_id, lon, lat in data:
            self.coords[node_id] = (lon, lat)
139848
function getAllNearPositions(position) {
    return [[-1, -1], [0, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [0, 1], [1, 1] // Below positions
    ].map(function (toAdd) {
        return {
            x: position.x + toAdd[0],
            y: position.y + toAdd[1]
        };
    });
}