<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Egmara Antunes dos Santos on Medium]]></title>
        <description><![CDATA[Stories by Egmara Antunes dos Santos on Medium]]></description>
        <link>https://medium.com/@egmara-santos?source=rss-1219a436a3a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yIYw0PjXMBBK8zL5</url>
            <title>Stories by Egmara Antunes dos Santos on Medium</title>
            <link>https://medium.com/@egmara-santos?source=rss-1219a436a3a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:10:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@egmara-santos/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Python to check geographic coordinates on a KML map]]></title>
            <link>https://egmara-santos.medium.com/using-python-to-check-geographic-coordinates-on-a-kml-map-baab4510a958?source=rss-1219a436a3a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/baab4510a958</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[geopandas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Egmara Antunes dos Santos]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 21:28:13 GMT</pubDate>
            <atom:updated>2021-01-14T21:28:13.714Z</atom:updated>
            <content:encoded><![CDATA[<p><em>My name is Egmara and I’m a Data Scientist at Delivery Center. Python is a language that I use a lot on a day-to-day basis and now, I’m going to show you an example of how this powerful language can be useful!</em></p><h3>The need to check geographic coordinates</h3><p>Delivery Center is a Brazilian company that acts as an integrating platform for Marketplaces such as iFood, Rappi and several others. Through this platform, sellers are able to manage their orders, coming from all these marketplaces in a single environment. Therefore, when we receive a new order it is important that the platform is able to recognize whether the geographic location (latitude and longitude, postal code, etc.) belongs to the established delivery area.</p><p>In many approaches, it is desirable to verify whether a geographic location belongs to a specific map file type called KML (Keyhole Markup Language). KML is a file format used to display geographic data and maps. In order to check coordinates of a latitude and longitude dataset in a map KML file, let’s use Python!</p><h3><strong>How can Python help you?</strong></h3><p><a href="https://geopandas.org/"><strong>GeoPandas</strong></a> is an open source project to work with geospatial data in Python. Geometric data types are used, such as <strong>Point</strong> or <strong>Polygon</strong>. GeoPandas extends the datatypes used by Pandas to allow spatial operations on these geometric types. The manipulation and analysis of objects are performed by the <a href="https://pypi.org/project/Shapely/"><strong>Shapely</strong></a> library.</p><h3><strong>Walk-through</strong></h3><h4>Installing Packages</h4><p>You can start by installing Pandas, GeoPandas and Shapely:</p><pre>python3 -m pip install geopandas<br>python3 -m pip install </pre><p>To import libraries, you can do:</p><pre>import geopandas as gpd<br>from shapely.geometry import Point, Polygon<br>import pandas as pd</pre><h4>Reading dataset and KML file</h4><p>Suppose you have a map KML file, called ‘my_map.kml’, and a latitude and longitude dataset, called ‘lat_long_dataset.csv’.</p><p><strong>Use GeoPandas to read the KML map and assign the result to an object:</strong></p><pre>gpd.io.file.fiona.drvsupport.supported_drivers[&#39;KML&#39;] = &#39;rw&#39;<br>my_map = gpd.read_file(&#39;my_map.kml&#39;, driver=&#39;KML&#39;)<br>my_map</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*QYGwqA6OzkFHmY7aerGCWw.png" /></figure><p>The my_map object is a GeoDataFrame and the column called ‘geometry’ is a geometric data type, a Polygon.</p><pre>type(my_map)</pre><pre>geopandas.geodataframe.GeoDataFrame</pre><p>To read the latitude and longitude dataset, use Pandas:</p><pre>locations = pd.read_csv(&#39;lat_long_dataset.csv&#39;)<br>locations</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*gIA6B3ax98oPCokq3jPRJA.png" /></figure><h4>Preparing the dataset</h4><p>We’re almost ready! Now, you need to convert each location data (latitude and longitude columns) into a geometric point:</p><pre>geometric_points = []<br>for xy in zip(locations[&#39;longitude&#39;], locations[&#39;latitude&#39;]):<br>   geometric_points.append(Point(xy))</pre><p>Add the geometric_points list to a column of a new GeoDataFrame:</p><pre>geo_locations = gpd.GeoDataFrame(locations,<br>                                 crs = {&#39;init&#39;: &#39;epsg:4326&#39;},<br>                                 geometry = geometric_points)<br>geo_locations</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*AfO6i1wovSYcRYSLper4zA.png" /></figure><h4>Checking geographic coordinates</h4><p>To check which locations of the dataset belong to the region of the polygon (KML map), the contains() method is the answer! This method returns ‘True’ if a data type Point belongs to the region and ‘False’, otherwise. Create a new Boolean column in your GeoDataFrame:</p><pre>for i in range(0, len(geo_locations)):<br>    point = geo_locations.geometry.loc[i]<br>    check = my_map.contains(point).values<br>    geo_locations[&#39;in_my_map&#39;].loc[i] = check</pre><pre>geo_locations.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*BQPp3kBxf2QgUlzvsbeoSw.png" /></figure><p>Therefore, the GeoDataFrame has a column that indicates whether the geometrical points belong to the KML map or not. In addition, the number of points that belong to the map is:</p><pre>print(sum(geo_locations.in_my_map == True))</pre><pre>99</pre><p>and the number of points that do not belong to the map is:</p><pre>print(sum(geo_locations.in_my_map == False))</pre><pre>1</pre><h3>Viewing the KML map and dataset with Folium!</h3><p>According to the previous step, only one place does not belong to the KML zone. Let’s see it?</p><p>Folium is a very useful library for viewing maps in the GeoJSON format. We can convert our KML file, ‘my_map.kml’, into a GeoJSON, ‘my_map.geojson’ using this <a href="https://mygeodata.cloud/converter/kml-to-geojson">tool</a>. Following some steps <a href="https://medium.com/@datalivre/folium-d6036a9ad29c">here</a>, you can view the map and the dataset!</p><p>To import Folium and create an image, you can do:</p><pre>import folium<br>fig = folium.Map(width=900, height=600)</pre><p>Read ‘my_map.geojson’ and add it to the image:</p><pre>geo_json_map = json.load(open(&#39;my_map.geojson&#39;))<br>folium.Choropleth(<br>    geo_data = geo_json_map,<br>    fill_color = &quot;steelblue&quot;,<br>    fill_opacity = 0.4,<br>    line_color = &quot;steelblue&quot;,<br>    line_opacity = 0.9<br>).add_to(fig)</pre><p>Now, add the points from the dataset:</p><pre>points = geo_locations[[&#39;latitude&#39;, &#39;longitude&#39;]].values.tolist()<br>for point in range(0, len(points)):<br> folium.Marker(locationlist[point]).add_to(fig)</pre><pre>fig</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*3a_p_rg2D_grJdvPEUU1sw.png" /></figure><p>Nice! Indeed, we can see that only one point is outside our KML zone, according to GeoPandas in the previous section.</p><p>I hope this helped! Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baab4510a958" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizando Python para verificar coordenadas geográficas em um mapa KML]]></title>
            <link>https://egmara-santos.medium.com/utilizando-python-para-verificar-coordenadas-geogr%C3%A1ficas-em-um-mapa-kml-c4d61541e5ce?source=rss-1219a436a3a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4d61541e5ce</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[geopandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mapas]]></category>
            <dc:creator><![CDATA[Egmara Antunes dos Santos]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 21:25:38 GMT</pubDate>
            <atom:updated>2021-01-14T21:25:38.704Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Me chamo Egmara e sou Cientista de Dados no Delivery Center. Utilizo muito a linguagem Python no meu dia a dia e no post de hoje vou mostrar mais um exemplo de como esta poderosa linguagem pode ser útil!</em></p><h3>A necessidade de checar coordenadas</h3><p>O Delivery Center é uma empresa que atua como uma plataforma integradora de Marketplaces como iFood, Rappi, B2W, Mercado Livre e diversos outros. Através dela, lojistas podem controlar sua operação de pedidos vindos destes marketplaces em um único ambiente, além de ter acesso a serviços de melhoria nos anúncios do seu catálogo e delivery com nossos entregadores parceiros em grandes shoppings, os chamados Hubs.</p><p>Sendo assim, é fundamental que quando nós consumidores realizamos uma compra em determinado e-commerce, a plataforma consiga reconhecer se a nossa localização geográfica (latitude e longitude, código postal, etc) pertence a área de entrega estabelecida pelo próprio e-commerce, Hub ou lojista.</p><p><strong>Muitas vezes deseja-se verificar se uma localização geográfica pertence a um determinado mapa, cuja representação é um arquivo no formato KML (<em>Keyhole Markup Language</em>). Este é um formato criado para armazenar dados geográficos e mapas.</strong></p><p>Neste artigo, apresento uma forma de realizar essa verificação para um conjunto de pontos de latitude e longitude em uma região representada por um arquivo KML de mapa.</p><h3>Como o Python pode ajudar?</h3><p>Vou utilizar o <a href="https://geopandas.org/"><strong>GeoPandas</strong></a>, que é um projeto de código aberto para facilitar trabalhos com dados geoespaciais. Estes dados são variáveis no Python dos tipos ponto geométrico (<strong>Point</strong>) ou polígonos (<strong>Polygon</strong>), por exemplo. O GeoPandas permite operações espaciais em DataFrames com esses tipos de dados geométricos. A manipulação e análise de objetos de um DataFrame do GeoPandas são feitas pela biblioteca <a href="https://pypi.org/project/Shapely/"><strong>Shapely</strong></a>.</p><h3>Mãos a obra!</h3><h4>Carregando bibliotecas</h4><p>Você pode começar instalando o GeoPandas e o Shapely via terminal:</p><pre>python3 -m pip install geopandas<br>python3 -m pip install shapely</pre><p>Agora, carregue o GeoPandas, algumas funções do Shapely e o nosso amigo Pandas em seu ambiente Python:</p><pre>import geopandas as gpd<br>from shapely.geometry import Point, Polygon<br>import pandas as pd</pre><h4>Lendo o dataset e o KML</h4><p>Suponha que você possua um arquivo KML que represente um mapa, chamado de<strong> </strong>‘meu_mapa.kml’, e um arquivo CSV de localizações geográficas de latitude e longitude, chamado de<strong> </strong>‘localizacoes.csv’.</p><p><strong>Utilize o GeoPandas para ler o arquivo KML e atribua o resultado a uma variável:</strong></p><pre>gpd.io.file.fiona.drvsupport.supported_drivers[&#39;KML&#39;] = &#39;rw&#39;<br>meu_mapa = gpd.read_file(&#39;meu_mapa.kml&#39;, driver=&#39;KML&#39;)<br>meu_mapa</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*HutjQcpVbbgDbBkwepDznA.png" /></figure><p>A variável meu_mapa é um GeoDataFrame e a coluna ‘geometry’ contém a forma geométrica que representa o mapa KML, um polígono.</p><pre>type(meu_mapa)</pre><pre>geopandas.geodataframe.GeoDataFrame</pre><p>Para ler o dataset de pontos com localizações de latitude e longitude, utilize o Pandas:</p><pre>localizacoes = pd.read_csv(&#39;localizacoes.csv&#39;)<br>localizacoes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*B4ZYP1YG3N3xoRo0DUqzqg.png" /></figure><h4>O bom e velho tratamento dos dados</h4><p>Está quase tudo pronto para você realizar a checagem das localizações no mapa disponibilizado! Para que isso seja possível, você precisa converter cada uma dessas localizações em uma variável do tipo Point:</p><pre>pontos_geometricos = []<br>for xy in zip(localizacoes[&#39;longitude&#39;], localizacoes[&#39;latitude&#39;]):<br>    pontos_geometricos.append(Point(xy))</pre><p>e incluir esta lista em uma coluna de um GeoDataFrame para as localizações:</p><pre>localizacoes_geo = gpd.GeoDataFrame(localizacoes,<br>                                    crs = {&#39;init&#39;: &#39;epsg:4326&#39;},<br>                                    geometry = pontos_geometricos)<br>localizacoes_geo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*QqOuXe15UG4GFvs3LC9nZw.png" /></figure><h4>Verificando as localizações no polígono!</h4><p>Para verificar quais localizações do conjunto de dados pertencem a região do polígono representado pela variável meu_mapa (mapa KML), o método contains() possui a solução para isto! Este retorna ‘True’ caso um ponto do tipo Point pertença a região e ‘False’, caso contrário. Utilize este método e crie uma nova coluna booleana chamada no GeoDataFrame:</p><pre>for i in range(0, len(localizacoes_geo)):<br>    ponto = localizacoes_geo.geometry.loc[i]<br>    check = meu_mapa.contains(ponto).values<br>    localizacoes_geo[&quot;pertence_ao_mapa&quot;].loc[i] = check</pre><pre>localizacoes_geo.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*UotEL8oCU_crOzspLgNUzA.png" /></figure><h4>Concluindo a checagem!</h4><p>Pronto! Agora o GeoDataFrame localizacoes_geo possui uma coluna que afirma se a localização geográfica pertence ou não ao mapa KML. Além disso, as quantidades de localizações dentro e fora do mapa são mostradas abaixo:</p><pre>print(&quot;Pontos dentro da região KML: &quot;, sum(localizacoes_geo.pertence_ao_mapa == True))<br>print(&quot;Pontos fora da região KML: &quot;, sum(localizacoes_geo.pertence_ao_mapa == False))</pre><pre>Pontos dentro da região KML:  99<br>Pontos fora da região KML:  1</pre><h3>Visualizando o KML e o dataset com o Folium!</h3><p>Concluímos anteriormente que somente uma localização não pertence a região KML. Vamos visualizar esse dado?</p><p>O Folium é uma biblioteca bastante útil para a visualização de mapas em formato GeoJSON. Podemos converter o nosso arquivo KML, ‘meu_mapa.kml’, em um GeoJSON, ‘meu_mapa.geojson’ usando este <a href="https://mygeodata.cloud/converter/kml-to-geojson">link</a>. Seguindo alguns passos deste belo tutorial <a href="https://medium.com/@datalivre/folium-d6036a9ad29c">aqui</a> do Medium, você consegue visualizar o mapa e o dataset!</p><p>Importe a biblioteca de visualização Folium e defina uma figura:</p><pre>import folium<br>fig = folium.Map(width=900, height=600)</pre><p>Leia o arquivo ‘meu_mapa.geojson’ e o adicione na figura:</p><pre>geo_json_mapa = json.load(open(&#39;meu_mapa.geojson&#39;))<br>folium.Choropleth(<br>    geo_data = geo_json_mapa,<br>    fill_color = &quot;steelblue&quot;,<br>    fill_opacity = 0.4,<br>    line_color = &quot;steelblue&quot;,<br>    line_opacity = 0.9<br>).add_to(fig)</pre><p>Por fim, adicione seus pontos na figura!</p><pre>pontos = localizacoes_geo[[&#39;latitude&#39;, &#39;longitude&#39;]].values.tolist()<br>for point in range(0, len(pontos)):<br>    folium.Marker(locationlist[point]).add_to(fig)</pre><pre>fig</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*3a_p_rg2D_grJdvPEUU1sw.png" /></figure><p>Legal! Podemos ver que de fato somente um ponto está fora da nossa região KML, como o GeoPandas havia nos informado no GeoDataFrame localizacoes_geo!</p><p>Obrigada pela leitura e até a próxima!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4d61541e5ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>