Skip to content

Maps

OpenMap #

Bases: BaseReader

打开地图阅读器。

从overpass api(osm)获取给定位置/区域的地图要素。

Parameters:

Name Type Description Default
如果你不确定搜索标签和tag_values,请访问https

//taginfo.openstreetmap.org/tags

required
Source code in llama_index/readers/maps/base.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class OpenMap(BaseReader):
    """打开地图阅读器。

从overpass api(osm)获取给定位置/区域的地图要素。

Args:
    localarea(str) - 你要搜索的区域或位置
    tag_values(str) - 给定区域的过滤器
    search_tag(str)  - 你要查找的标签

    如果你不确定搜索标签和tag_values,请访问https://taginfo.openstreetmap.org/tags

    remove_keys(list) - 需要从响应中移除的键列表
                        默认情况下将移除以下键 ['nodes','geometry','members']"""

    def __init__(self) -> None:
        """使用参数进行初始化。"""
        super().__init__()

    @staticmethod
    def _get_user() -> str:
        # choose from all lowercase letter
        letters = string.ascii_lowercase
        return "".join(random.choice(letters) for i in range(10))

    @staticmethod
    def _get_latlon(locarea: str, user_agent: str) -> tuple:
        try:
            from geopy.geocoders import Nominatim
        except ImportError:
            raise ImportError("install geopy using `pip3 install geopy`")

        geolocator = Nominatim(user_agent=user_agent)
        location = geolocator.geocode(locarea)
        return (location.latitude, location.longitude) if location else (None, None)

    def load_data(
        self,
        localarea: str,
        search_tag: Optional[str] = "amenity",
        remove_keys: Optional[List] = ["nodes", "geometry", "members"],
        tag_only: Optional[bool] = True,
        tag_values: Optional[List] = [""],
        local_area_buffer: Optional[int] = 2000,
    ) -> List[Document]:
        """这个加载器将为你提供给定位置在开放街地图中的所有节点数值。

Args:
localarea(str) - 你要搜索的区域或位置
search_tag(str)  - 你要查找的标签
如果你不确定搜索标签和标签数值,访问 https://taginfo.openstreetmap.org/tags

remove_keys(list) - 需要从响应中移除的键的列表
                    默认情况下,这些键将被移除 ['nodes','geometry','members']

tag_only(bool) - 如果为True,则返回具有标签的节点,如果为False,则返回所有节点
tag_values(str) - 给定区域的过滤器
local_area_buffer(int) - 你希望覆盖的范围(默认为2000(2公里))
"""
        try:
            from osmxtract import location, overpass
            from osmxtract.errors import OverpassBadRequest
        except ImportError:
            raise ImportError("install osmxtract using `pip3 install osmxtract`")

        null_list = ["", "null", "none", None]
        extra_info = {}
        local_area = localarea

        if local_area.lower().strip() in null_list:
            raise Exception("The Area should not be null")

        user = self._get_user()
        lat, lon = self._get_latlon(local_area, user)
        try:
            bounds = location.from_buffer(lat, lon, buffer_size=int(local_area_buffer))
        except TypeError:
            raise TypeError("Please give valid location name or check for spelling")

        # overpass query generation and execution
        tag_values = [str(i).lower().strip() for i in tag_values]
        query = overpass.ql_query(
            bounds, tag=search_tag.lower(), values=tag_values, timeout=500
        )

        extra_info["overpass_query"] = query
        try:
            response = overpass.request(query)

        except OverpassBadRequest:
            raise TypeError(
                f"Error while executing the Query {query} please check the Args"
            )

        res = response["elements"]

        _meta = response.copy()
        del _meta["elements"]
        extra_info["overpass_meta"] = str(_meta)
        extra_info["lat"] = lat
        extra_info["lon"] = lon
        # filtering for only the tag values
        filtered = [i for i in res if "tags" in i] if tag_only else res

        for key in remove_keys:
            [i.pop(key, None) for i in filtered]
        if filtered:
            return Document(text=str(filtered), extra_info=extra_info)
        else:
            return Document(text=str(res), extra_info=extra_info)

load_data #

load_data(
    localarea: str,
    search_tag: Optional[str] = "amenity",
    remove_keys: Optional[List] = [
        "nodes",
        "geometry",
        "members",
    ],
    tag_only: Optional[bool] = True,
    tag_values: Optional[List] = [""],
    local_area_buffer: Optional[int] = 2000,
) -> List[Document]

这个加载器将为你提供给定位置在开放街地图中的所有节点数值。

Args: localarea(str) - 你要搜索的区域或位置 search_tag(str) - 你要查找的标签 如果你不确定搜索标签和标签数值,访问 https://taginfo.openstreetmap.org/tags

remove_keys(list) - 需要从响应中移除的键的列表 默认情况下,这些键将被移除 ['nodes','geometry','members']

tag_only(bool) - 如果为True,则返回具有标签的节点,如果为False,则返回所有节点 tag_values(str) - 给定区域的过滤器 local_area_buffer(int) - 你希望覆盖的范围(默认为2000(2公里))

Source code in llama_index/readers/maps/base.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    def load_data(
        self,
        localarea: str,
        search_tag: Optional[str] = "amenity",
        remove_keys: Optional[List] = ["nodes", "geometry", "members"],
        tag_only: Optional[bool] = True,
        tag_values: Optional[List] = [""],
        local_area_buffer: Optional[int] = 2000,
    ) -> List[Document]:
        """这个加载器将为你提供给定位置在开放街地图中的所有节点数值。

Args:
localarea(str) - 你要搜索的区域或位置
search_tag(str)  - 你要查找的标签
如果你不确定搜索标签和标签数值,访问 https://taginfo.openstreetmap.org/tags

remove_keys(list) - 需要从响应中移除的键的列表
                    默认情况下,这些键将被移除 ['nodes','geometry','members']

tag_only(bool) - 如果为True,则返回具有标签的节点,如果为False,则返回所有节点
tag_values(str) - 给定区域的过滤器
local_area_buffer(int) - 你希望覆盖的范围(默认为2000(2公里))
"""
        try:
            from osmxtract import location, overpass
            from osmxtract.errors import OverpassBadRequest
        except ImportError:
            raise ImportError("install osmxtract using `pip3 install osmxtract`")

        null_list = ["", "null", "none", None]
        extra_info = {}
        local_area = localarea

        if local_area.lower().strip() in null_list:
            raise Exception("The Area should not be null")

        user = self._get_user()
        lat, lon = self._get_latlon(local_area, user)
        try:
            bounds = location.from_buffer(lat, lon, buffer_size=int(local_area_buffer))
        except TypeError:
            raise TypeError("Please give valid location name or check for spelling")

        # overpass query generation and execution
        tag_values = [str(i).lower().strip() for i in tag_values]
        query = overpass.ql_query(
            bounds, tag=search_tag.lower(), values=tag_values, timeout=500
        )

        extra_info["overpass_query"] = query
        try:
            response = overpass.request(query)

        except OverpassBadRequest:
            raise TypeError(
                f"Error while executing the Query {query} please check the Args"
            )

        res = response["elements"]

        _meta = response.copy()
        del _meta["elements"]
        extra_info["overpass_meta"] = str(_meta)
        extra_info["lat"] = lat
        extra_info["lon"] = lon
        # filtering for only the tag values
        filtered = [i for i in res if "tags" in i] if tag_only else res

        for key in remove_keys:
            [i.pop(key, None) for i in filtered]
        if filtered:
            return Document(text=str(filtered), extra_info=extra_info)
        else:
            return Document(text=str(res), extra_info=extra_info)