投稿時間:2022-07-01 23:35:46 RSSフィード2022-07-01 23:00 分まとめ(46件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] povo2.0、期間限定「お試しトッピング」 30日間1GBを499円 https://www.itmedia.co.jp/business/articles/2207/01/news161.html itmedia 2022-07-01 22:35:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] ジョイフル、YouTuberヒカルが愛した「べんてん屋 うま味噌ラーメン」を発売 https://www.itmedia.co.jp/business/articles/2207/01/news086.html itmedia 2022-07-01 22:26:00
AWS AWS Database Blog Backfilling an Amazon DynamoDB Time to Live attribute using Amazon EMR: Part 2 https://aws.amazon.com/blogs/database/part-2-backfilling-an-amazon-dynamodb-time-to-live-attribute-using-amazon-emr/ Backfilling an Amazon DynamoDB Time to Live attribute using Amazon EMR Part Amazon DynamoDB is a fully managed serverless key value NoSQL database designed to run high performance applications at any scale DynamoDB can store and retrieve any amount of data As the data grows and becomes cold many use cases such as session management or order management require archival of the older unneeded items DynamoDB has a feature … 2022-07-01 13:58:53
AWS AWS Startups Blog ICYMI: Meet the Inaugural Cohort of the Impact Accelerator, Come with Us to AWS Summit Atlanta, and More https://aws.amazon.com/blogs/startups/icymi-meet-the-inaugural-cohort-of-the-impact-accelerator-come-with-us-to-aws-summit-atlanta-and-more/ ICYMI Meet the Inaugural Cohort of the Impact Accelerator Come with Us to AWS Summit Atlanta and MoreEach month the AWS Startups blog is packed with announcements resources stories and videos Let s get caught up on anything that you might have missed in June 2022-07-01 13:46:10
AWS AWS Amazon EC2 Inf1 Instances | Amazon Web Services https://www.youtube.com/watch?v=OskQJTlKJbk Amazon EC Inf Instances Amazon Web ServicesAmazon EC Inf instances based on AWS Inferentia chip provide high performance and lowest cost inference in the cloud Learn more Subscribe More AWS videos More AWS events videos ABOUT AWSAmazon Web Services AWS is the world s most comprehensive and broadly adopted cloud platform offering over fully featured services from data centers globally Millions of customers ーincluding the fastest growing startups largest enterprises and leading government agencies ーare using AWS to lower costs become more agile and innovate faster MachineLearning Inference AWS AmazonWebServices CloudComputing 2022-07-01 13:41:09
Docker dockerタグが付けられた新着投稿 - Qiita 11.7.2 Multiple base classes [class.mi] C++N4910:2022 (159) p289.cpp https://qiita.com/kaizen_nagoya/items/9ca333b2875a61c8f13e class 2022-07-01 22:39:06
Docker dockerタグが付けられた新着投稿 - Qiita 11.7.1 General [class.derived.general] C++N4910:2022 (158) p288.cpp https://qiita.com/kaizen_nagoya/items/0e90898799984c61abea class 2022-07-01 22:26:32
Docker dockerタグが付けられた新着投稿 - Qiita 11.6 Local class declarations [class.local] C++N4910:2022 (157) p287.cpp https://qiita.com/kaizen_nagoya/items/6d8954c05c0b2e2e9c7f class 2022-07-01 22:22:23
Docker dockerタグが付けられた新着投稿 - Qiita 11.5.2 Anonymous unions [class.union.anon] C++N4910:2022 (156) p286.cpp https://qiita.com/kaizen_nagoya/items/ad1c0bd36a9f1eba35f1 anonymous 2022-07-01 22:18:29
Git Gitタグが付けられた新着投稿 - Qiita 【#16 エンジニア転職学習】Git/Github add, commitコマンド https://qiita.com/Chika110/items/f2366e349d973ae2d984 chika 2022-07-01 22:09:42
海外TECH MakeUseOf 4 Smartphone Specs That Aren't as Important as You Think https://www.makeuseof.com/smartphone-specs-arent-as-important-as-you-think/ learn 2022-07-01 13:45:13
海外TECH MakeUseOf What's the Difference Between Pixel, Vector, and Live Brushes in Adobe Fresco? https://www.makeuseof.com/adobe-fresco-pixel-vector-live-brushes-difference/ adobe 2022-07-01 13:30:15
海外TECH MakeUseOf Wondershare Recoverit Handles Deleted Video Recovery, Photo Recovery, and More https://www.makeuseof.com/wondershare-recoverit-10/ recoverit 2022-07-01 13:30:14
海外TECH MakeUseOf How to Download and Play Fall Guys on Your Nintendo Switch https://www.makeuseof.com/download-fall-guys-on-nintendo-switch/ online 2022-07-01 13:22:50
海外TECH MakeUseOf Bioheart Review: The Complete Heart Health Monitoring Device https://www.makeuseof.com/bioheart-review/ ambitious 2022-07-01 13:05:14
海外TECH MakeUseOf What Is Leakware? Here's What You Need to Know https://www.makeuseof.com/what-is-leakware/ caveat 2022-07-01 13:01:13
海外TECH DEV Community Showing MapBox map with React. 🗺️ https://dev.to/franklin030601/showing-mapbox-map-with-react-55g Showing MapBox map with React ️The purpose of this post is to teach how to use the MapBox GL JS library to display interactive maps in React JS applications In this case we are going to display a map and add an event to it which is executed at the moment of double clicking a marker is placed at that position that was just double clicked Note This post requires you to know the basics of React with TypeScript basic hooks and fetch requests Any kind of Feedback or improvement is welcome thanks and hope you enjoy the article Table of contents Technologies to be used Before you start coding Creating the project First steps Creating the component to display the map Showing the map on screen Keeping the reference to the map container Why do we need to keep the reference Initializing MapBox Adding a marker at the initial position Before our component grows Listening for the load event in the map Creating the function to add markers Showing the marker Adding a new marker on the map when double clicked Conclusion Source code   Technologies to be used ️React JS v ️Vite JS ️TypeScript ️MapBox ️CSS You can find the styles in the repository at the end of this post   Before you start coding Before we start working with the code we have to do a couple of things to be able to use the MapBox map You have to create a MapBox account In your account you will look for the access token that MapBox creates by default or if you prefer you can create a new access token Save this access token to use it later   Creating the component to display the map We will name the project show mapbox optional you can name it whatever you like npm init vite latestWe create the project with Vite JS and select React with TypeScript Then we execute the following command to navigate to the directory just created cd show mapboxThen we install the dependencies npm installThen we open the project in a code editor in my case VS code code   First steps We need to install MapBox in our application npm i mapbox glAnd since we are using TypeScript we need to install the MapBox types npm i D types mapbox glInside the folder src App tsx we delete all the content of the file and place a h that says Hello world in the meantime const App gt return lt div gt lt h gt Hello World lt h gt lt div gt export default AppNote It is necessary to place the MapBox styles so that when we are using the map it looks the best way The best will be to import the styles in the src main tsx file at the top of our application Line to place import mapbox gl dist mapbox gl css This is what the src main tsx file would look likeimport React from react import ReactDOM from react dom client import App from App import mapbox gl dist mapbox gl css import index css ReactDOM createRoot document getElementById root render lt React StrictMode gt lt App gt lt React StrictMode gt   Creating the component to display the map We create the src components folder and create the MapView tsx file And the only thing we need to display the map is a div tag Note Before we start displaying the map this component must be given styles a height and a width so that we can then display the map correctly export const MapView gt return lt div className map gt   Showing the map on screen To display the map we will need to use hooks The first one will be the useRef We need useRef to store the reference of the div where the map will be rendered The other hook is the useEffect hook We will use this hook to initialize the map   Keeping the reference to the map container We use the hook useRef for this task as follows import useRef from react export const MapView gt const mapRef useRef lt HTMLDivElement gt null return lt div ref mapRef className map gt   Why do we need to keep the reference Bueno podríamos solo colocar solo un ID al div y ya con eso funcionaria El problema sera cuando queramos usar mas de un mapa Si usamos más de un componente MapView solo se renderizaría un solo mapa por que tienen el mismo ID y para evitar eso usamos el hook useRef ya que cada vez que reutilizamos el componente MapView se creara una nueva referencia   Initializing MapBox We create the src utils folder and create a new file called initMap ts and there we will build the function to initialize the map This function has to receive container HTML element in this case the div where the map will be rendered coords coordinates of the place They have to be of type array of two numbers where the first position is the longitude and the second position is the latitude import Map from mapbox gl export const initMap container HTMLDivElement coords number number gt Inside the function we are going to return a new instance of Map We return it because we are going to need that instance to make more events and actions In the case that you only need to show the map and already it won t be necessary to return anything import Map from mapbox gl export const initMap container HTMLDivElement coords number number gt return new Map The Map class requires certain options container the HTML element where the map will be rendered its value will be the container that comes to us by parameter of the function style type of style of the map in this case I will use the dark in the MapBox documentation there are more styles pitchWithRotate is the tilt control of the map in this case we want to remove it so we put false center are the coordinates where the map will be positioned when initialized its value will be the coords that comes to us by parameter of the function zoom the initial zoom of the map the levels go from to accessToken the token that we saved previously So I recommend you to save this token in an environment variable and use this variable in this accessToken property doubleClickZoom action that is triggered when double clicking by default is to increase the zoom but we will set it to false since we will use the action of the double click for another task And that would be our function ready to use import Map from mapbox gl export const initMap container HTMLDivElement coords number number gt return new Map container style mapbox styles mapbox dark v pitchWithRotate false center coords zoom accessToken import meta env VITE KEY as string doubleClickZoom false Now in our MapView component we will use the useEffect to call the function that we have created Inside the useEffect we will make a condition where only if the value of useRef exists we will initialize our map In the initMap function we send the HTML element that is in the current property of mapRef then we send the coordinates longitude latitude import useRef from react import useMap from hook useMap export const MapView gt const mapRef useRef lt HTMLDivElement gt null useEffect gt if mapRef current initMap mapRef current return lt div ref mapRef className map gt Now we would see the map on screen as in this image Well what now How about we add some events to add bookmarks   Adding a marker at the initial position Before creating events with the map we have to keep the reference to the Map instance for that we will use again useRef We create a new reference called mapInitRef which will be of type map or null The initMap function returns the Map instance so we will assign this instance to mapInitRef const mapInitRef useRef lt Map null gt null useEffect gt if mapRef current mapInitRef current initMap mapRef current   Before our component grows At this point it will be better to refactor our code creating a custom hook to handle the map logic and leave our MapView component clean We create the src hooks folder and inside we create the useMap ts file and move the MapView logic to the useMap ts file This custom hook receives as parameter the container where the map will be rendered Now we replace the word mapRef by container import useEffect useRef from react import Map from mapbox gl import initMap from utils initMap export const useMap container React RefObject lt HTMLDivElement gt gt const mapInitRef useRef lt Map null gt null useEffect gt if container current mapInitRef current initMap container current Then we make the call of the hook in our component MapView And thus we will have our component much more readable import useRef from react import useMap from hook useMap export const MapView gt const mapRef useRef lt HTMLDivElement gt null useMap mapRef return lt div ref mapRef className map gt   Listening for the load event in the map Well so far we already have the reference to the map instance available Now what we want to do is that when we load the map a marker is displayed on the screen For this the Map instance has the method on that allows us to listen to certain events that are triggered in the map So first we create a useEffect useEffect gt Then we are going to make an evaluation where if the mapInitRef current exists that is to say that it has the value of the instance we execute the following event on useEffect gt mapInitRef current amp amp mapInitRef current on The on method in this case receives parameters type the action to listen to in this case it will be the load action since we want something to be executed when the map has already been loaded listener the function to execute when the action is listened useEffect gt mapInitRef current amp amp mapInitRef current on load gt Creating the function to add markers Now let s create a function to add markers to the map Inside the folder src utils we create the file generateNewMarker ts and add a new function This function receives as parameter lat latitude lng longitude map the map to add the marker to import Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt To create a marker we create a new instance of the Marker class which we send certain optional parameters color color of the marker scale size of the marker import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt new Marker color df scale Then we execute the setLngLat method to send it the longitude and latitude as an array to tell the marker where it should be placed import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt new Marker color df scale setLngLat lng lat And finally we call the addTo method to add it to the map we pass it the instance of the map that we received by parameter import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt new Marker color df scale setLngLat lng lat addTo map An extra would be to create a PopUp For it we make a new instance of the class Popup we save it in a constant which we send certain parameters that are optional closeButton show the close button we set it to false anchor the position where the PopUp should be shown in the marker import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt const popUp new Popup closeButton false anchor left new Marker color df scale setLngLat lng lat addTo map And to place custom content to the PopUp we will call the setHTML method and send it HTML as a string import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt const popUp new Popup closeButton false anchor left setHTML lt div class popup gt You click here lt br gt lng lat lt div gt new Marker color df scale setLngLat lng lat addTo map Finally to the instance of the Marker before the addTo method we place the setPopup method and send it the popUp constant import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt const popUp new Popup closeButton false anchor left setHTML lt div class popup gt You click here lt br gt lng lat lt div gt new Marker color df scale setLngLat lng lat setPopup popUp addTo map It s time to call this method   Showing the marker In our hook useMap inside the useEffect where we were creating adding the event to listen to the map when it loads for the first time we call the generateNewMarker method useEffect gt mapInitRef current amp amp mapInitRef current on load gt generateNewMarker To this method we send an object containing map we send mapInitRef current since it is the instance of the map the second parameter we send mapInitRef current getCenter This function returns an array of two numbers that are the longitude and latitude these numbers are those that we passed at the beginning at the time of initializing the map for which we spread them with the spread operator useEffect gt mapInitRef current amp amp mapInitRef current on load gt generateNewMarker map mapInitRef current mapInitRef current getCenter Finally it is good practice that when we are listening to events within a useEffect when the component is disassembled which in this case will not happen because we only have one view which is the map it is necessary to stop listening to the event and not execute anything useEffect gt mapInitRef current amp amp mapInitRef current on load gt generateNewMarker map mapInitRef current mapInitRef current getCenter return gt mapInitRef current off load generateNewMarker  This is what the marker would look like on our map   Adding a new marker on the map when double clicked This will be very simple since we have almost everything done It is only necessary to add a new effect in our custom hook And following the same practices as when we listened to the load event before We validate that mapInitRef contains the map instance We call the on method to listen for the dblclick event Now the listener that is executed gives us access to the longitude and latitude which come as an array of two numbers which we can unstructure from the listener We execute the function generateNewMarker To the function generateNewMarker we send the map which will have the value of the map instance found in mapInitRef current Then we spread the value of lngLat given to us by the listener We clean the effect with the return stopping listening to the dblclick event useEffect gt mapInitRef current amp amp mapInitRef current on dblclick lngLat gt generateNewMarker map mapInitRef current lngLat return gt mapInitRef current off dblclick generateNewMarker  This is how the markers would look on our map   Conclusion The whole process I just showed is one of the ways in which displaying a map with React JS can be done ️I hope I helped you understand how to perform this exercise thank you very much for making it this far I invite you to comment if you know any other different or better way how to make display a map with React JS And if you liked the content don t forget to support me by reacting to this post or sharing this post with someone who cares ️  Source code Franklin show map Application to display a map from the MapBox library and execute events to add markers on the map ️ Show MapBox map with React ️Application to display a map from the MapBox library and execute events to add markers on the map ️  Features ️View a full screen map Place a marker at the initial position when loading the map Add a new marker when double clicking on the map  Technologies React JSTypeScriptVite JSMapBox Installation Clone the repository you need to have Git installed git clone Install dependencies of the project npm installRun the project npm run devNote For running the tests use the following command npm run test Links ️Demo of the application Here s the link to the tutorial in case you d like to take a look at it eyes View on GitHub 2022-07-01 13:39:40
海外TECH DEV Community Mostrando mapa de MapBox con React. 🗺️ https://dev.to/franklin030601/mostrando-mapa-de-mapbox-con-react-82k Mostrando mapa de MapBox con React ️El propósito de esta publicación es enseñar como utilizar la librería de MapBox GL JS para mostrar mapas interactivos en aplicaciones de React JS En este caso vamos a mostrar un mapa y agregarle un evento que se ejecute al momento de dar doble click se coloque un marcador en esa posición a la que se acaba de dar doble click Nota Este post requiere que sepas las bases de React con TypeScript hooks básicos y peticiones con fetch Cualquier tipo de Feedback o mejora es bienvenido gracias y espero disfrutes el articulo Tabla de contenido Tecnologías a utilizar Antes de empezar a codear Creando el proyecto Primeros pasos Creando el componente para mostrar el mapa Mostrando el mapa en pantalla Manteniendo la referencia al contenedor del mapa ¿Por quénecesitamos mantener la referencia Inicializando MapBox Agregar un marcador en la posición inicial Antes de que crezca nuestro componente Escuchando el evento load en el mapa Creando la función para agregar marcadores Mostrando el marcador Agregar un nuevo marcador en el mapa cuando se haga doble click Conclusión Código fuente   Tecnologías a utilizar ️React JS version ️Vite JS ️TypeScript ️MapBox ️CSS vanilla Los estilos los encuentras en el repositorio al final de este post   Antes de empezar a codear Antes de empezar a trabajar con el código tenemos que hacer un par de cosas para poder utilizar el mapa de MapBox Tienes que crear una cuenta en MapBox En tu cuenta buscaras el access token que te crea MapBox por defecto o si lo prefieres puedes crear un nuevo token de acceso Guardar ese token de acceso para usarlo después   Creando el proyecto Al proyecto le colocaremos el nombre de show mapbox opcional tu le puedes poner el nombre que gustes npm init vite latestCreamos el proyecto con Vite JS y seleccionamos React con TypeScript Luego ejecutamos el siguiente comando para navegar al directorio que se acaba de crear cd show mapboxLuego instalamos las dependencias npm installDespués abrimos el proyecto en un editor de código en mi caso VS code code   Primeros pasos Necesitamos instalar MapBox en nuestra aplicación npm i mapbox glY como estamos usando TypeScript necesitamos instalar los tipos de MapBox npm i D types mapbox glDentro de la carpeta src App tsx borramos todo el contenido del archivo y colocamos un h que diga Hello world por mientras const App gt return lt div gt lt h gt Hello World lt h gt lt div gt export default AppNota Es necesario colocar los estilos de MapBox para que cuando estemos usando el mapa este se vea de la mejor manera Lo mejor sera importar los estilos en el archivo src main tsx en lo mas alto de nuestra aplicación Linea a colocar import mapbox gl dist mapbox gl css Asi se vería el archivo src main tsximport React from react import ReactDOM from react dom client import App from App import mapbox gl dist mapbox gl css import index css ReactDOM createRoot document getElementById root render lt React StrictMode gt lt App gt lt React StrictMode gt   Creando el componente para mostrar el mapa Creamos la carpeta src components y creamos el archivo MapView tsxY lo único que necesitamos para mostrar el mapa es una etiqueta divNota Antes de empezar a mostrar el mapa a este componente se le debe dar estilos un alto y un ancho para que luego podamos visualizar el mapa correctamente export const MapView gt return lt div className map gt   Mostrando el mapa en pantalla Para mostrar el mapa necesitaremos usar hooksEl primero sera el useRef Necesitamos useRef para guardar la referencia del div donde se va a renderizar el mapa El otro hook es el useEffect Usaremos este hook para inicializar el mapa   Manteniendo la referencia al contenedor del mapa Usamos el hook useRef para esta tarea de la siguiente manera import useRef from react export const MapView gt const mapRef useRef lt HTMLDivElement gt null return lt div ref mapRef className map gt   ¿Por quénecesitamos mantener la referencia Bueno podríamos solo colocar solo un ID al div y ya con eso funcionaria El problema sera cuando queramos usar mas de un mapa Si usamos más de un componente MapView solo se renderizaría un solo mapa por que tienen el mismo ID y para evitar eso usamos el hook useRef ya que cada vez que reutilizamos el componente MapView se creara una nueva referencia   Inicializando MapBox Creamos la carpeta src utils y creamos un nuevo archivo llamado initMap ts y ahíconstruiremos la función para inicializar el mapa Esta función tiene que recibir container elemento HTML en este caso el div donde se renderizaráel mapa coords coordenadas del lugar Tienen que ser de tipo array de dos números donde la primera posición es la longitud y la segunda posición es la latitud import Map from mapbox gl export const initMap container HTMLDivElement coords number number gt Dentro de la función vamos a retornar una nueva instancia de Map La retornamos ya que vamos a necesitar esa instancia para hacer mas eventos y acciones En el caso de que solo ocupes mostrar el mapa y ya no sera necesario retornar nada import Map from mapbox gl export const initMap container HTMLDivElement coords number number gt return new Map La clase Map requiere ciertos opciones container el elemento HTML donde se renderizaráel mapa su valor sera el container que nos llega por parámetro de la función style Tipo de estilo del mapa en este caso usare el dark en la documentación de MapBox vienen más estilos pitchWithRotate es el control de inclinación del mapa que en este caso lo queremos quitar por eso colocamos false center son las coordenadas donde se posicionaráel mapa al inicializarse su valor serán las coords que nos llega por parámetro de la función zoom el zoom inicial del mapa los niveles van de a accessToken el token que guardamos con anterioridad Por lo que te recomiendo guardar este token en una variable de entorno y usar dicha variable en esta propiedad de accesToken doubleClickZoom acción que se dispara al hacer doble click por defecto es el aumentar el zoom pero lo pondremos el false ya que usaremos la acción del doble click para otra tarea Y asi quedaría nuestra función lista para usarla import Map from mapbox gl export const initMap container HTMLDivElement coords number number gt return new Map container style mapbox styles mapbox dark v pitchWithRotate false center coords zoom accessToken import meta env VITE KEY as string doubleClickZoom false Ahora de vuela en nuestro componente MapView usaremos el useEffect para llamar la función que hemos creado Dentro del useEffect haremos una condición donde solo si existe el valor de useRef inicializaremos nuestro mapa En la función initMap mandamos el elemento HTML que se encuentra en la propiedad current de mapRef después mandamos las coordenadas longitud latitud import useRef from react import useMap from hook useMap export const MapView gt const mapRef useRef lt HTMLDivElement gt null useEffect gt if mapRef current initMap mapRef current return lt div ref mapRef className map gt Ahora veríamos el mapa en pantalla como en esta imagen Bueno y ahora que Que tal si agregamos unos eventos para agregar marcadores   Agregar un marcador en la posición inicial Antes de crear eventos con el mapa tenemos que mantener la referencia a la instancia de Map para eso usaremos nuevamente useRef Creamos una nueva referencia llamada mapInitRef que sera de tipo map o null La función initMap retorna la instancia del Map por lo que a mapInitRef le asignaremos dicha instancia const mapInitRef useRef lt Map null gt null useEffect gt if mapRef current mapInitRef current initMap mapRef current   Antes de que crezca nuestro componente En este punto sera mejor refactorizar nuestro código creando un custom hook para manejar la lógica del mapa y dejar limpio nuestro componente MapView Creamos la carpeta src hooks y dentro creamos el archivo useMap ts y movemos la lógica del MapView al archivo useMap ts Este custom hook recibe como parámetro el contenedor donde se renderizaráel mapa Ahora remplazamos la palabra mapRef por container import useEffect useRef from react import Map from mapbox gl import initMap from utils initMap export const useMap container React RefObject lt HTMLDivElement gt gt const mapInitRef useRef lt Map null gt null useEffect gt if container current mapInitRef current initMap container current Después hacemos la llamada del hook en nuestro componente MapView Y asi nos quedara nuestro componente mucho mas legible import useRef from react import useMap from hook useMap export const MapView gt const mapRef useRef lt HTMLDivElement gt null useMap mapRef return lt div ref mapRef className map gt   Escuchando el evento load en el mapa Bueno hasta ahora ya tenemos la referencia a la instancia del mapa a disposición Ahora lo que queremos hacer es que al cargar el mapa se muestre un marcador en pantalla Para esto la instancia de Map tiene el método on que nos permite escuchar ciertos eventos que se disparan en el mapa Asi que primero creamos un useEffect useEffect gt Luego vamos hacer una evaluación donde si el mapInitRef current existe o sea que tiene el valor de la instancia ejecutamos el siguiente evento on useEffect gt mapInitRef current amp amp mapInitRef current on El método on en este caso recibe parámetros type es la acción a escuchar en este caso sera la acción load ya que queremos que se ejecute algo cuando ya haya cargado el mapa listener la función a ejecutar cuando se escuche la acción useEffect gt mapInitRef current amp amp mapInitRef current on load gt Creando la función para agregar marcadores Ahora vamos a crear una función para agregar marcadores al mapa Dentro de la carpeta src utils creamos el archivo generateNewMarker ts y agregamos una nueva función Esta función recibe como parámetro lat latitud lng longitud map el mapa al cual agregar el marcador import Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt Para crear un marcador hacemos una nueva instancia de la clase Marker la cual le mandamos ciertos parámetros que son opcionales color color del marcador scale tamaño del marcador import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt new Marker color df scale Después ejecutamos el método setLngLat para mandarle la longitud y latitud como arreglo para decirle al marcador donde debe colocarse import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt new Marker color df scale setLngLat lng lat Y finalmente llamamos al método addTo para agregarlo al mapa le pasamos la instancia del mapa que recibimos por parámetro import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt new Marker color df scale setLngLat lng lat addTo map Un extra seria crearle un PopUp Para ello hacemos una nueva instancia de la clase Popup la guardamos en una constante la cual le mandamos ciertos parámetros que son opcionales closeButton mostrar el botón de cerrar lo colocamos el falso anchor la posición donde debe mostrase el PopUp en el marcador import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt const popUp new Popup closeButton false anchor left new Marker color df scale setLngLat lng lat addTo map Y para colocar contenido personalizado al PopUp llamaremos al método setHTML y le mandamos HTML como un string import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt const popUp new Popup closeButton false anchor left setHTML lt div class popup gt You click here lt br gt lng lat lt div gt new Marker color df scale setLngLat lng lat addTo map Finalmente a la instancia del Marker antes del método addTo colocamos el método setPopup y le mandamos la constante popUp import Popup Marker Map from mapbox gl export const generateNewMarker lat lng map lng number lat number map Map gt const popUp new Popup closeButton false anchor left setHTML lt div class popup gt You click here lt br gt lng lat lt div gt new Marker color df scale setLngLat lng lat setPopup popUp addTo map Es hora de llamar este método   Mostrando el marcador En nuestro hook useMap dentro del useEffect donde estábamos creando agregando el evento para escuchar el mapa cuando cargue por primera vez hacemos la llamada del método generateNewMarker useEffect gt mapInitRef current amp amp mapInitRef current on load gt generateNewMarker A este método le mandamos un objeto que contenga map le mapInitRef current ya que es la instancia del mapa el segundo parámetro mandamos mapInitRef current getCenter Esta función retorna un array de dos números que son la longitud y latitud estos números son los que le pasamos al principio al momento de inicializar el mapa por lo cual los esparcimos con el operador spread useEffect gt mapInitRef current amp amp mapInitRef current on load gt generateNewMarker map mapInitRef current mapInitRef current getCenter Por ultimo es buena practica que cuando estamos escuchando eventos dentro de un useEffect al momento de que se desmonte el componente que en este caso no va a pasar ya que solo tenemos una vista que es la del mapa es necesario dejar de escuchar el evento y no ejecutar nada useEffect gt mapInitRef current amp amp mapInitRef current on load gt generateNewMarker map mapInitRef current mapInitRef current getCenter return gt mapInitRef current off load generateNewMarker  Asi se vería el marcador en nuestro mapa   Agregar un nuevo marcador en el mapa cuando se haga doble click Esto sera muy sencillo ya que tenemos casi todo hecho Solo es necesario agregar un nuevo efecto en nuestro custom hook Y siguiendo las mismas practicas que cuando escuchamos el evento load anteriormente Hacemos la validación de que mapInitRef contenga la instancia del mapa Llamamos al método on para escuchar el evento de dblclick Ahora el listener que se ejecuta nos de acceso a la longitud y latitud que vienen como un array de dos números las cuales podemos desestructurar del listener Ejecutamos la función generateNewMarker A la función generateNewMarker le mandamos el map que tendráel valor de la instancia del mapa que se encuentra en mapInitRef current Después le esparcimos el valor de lngLat que nos otorga el listener Limpiamos el efecto con el return dejando de escuchar el evento dblclick useEffect gt mapInitRef current amp amp mapInitRef current on dblclick lngLat gt generateNewMarker map mapInitRef current lngLat return gt mapInitRef current off dblclick generateNewMarker  Asi se verían los marcadores en nuestro mapa   Conclusión Todo el proceso que acabo de mostrar es una de las formas en que se puede realizar el mostrar un mapa con React JS ️Espero haberte ayudado a entender como realizar este ejercicio muchas gracias por llegar hasta aquí Te invito a que comentes si es que conoces alguna otra forma distinta o mejor de como hacer mostrar un mapa con React JS Y si te gusto el contenido no olvides apoyarme reaccionando a esta publicación o compartiendo esta publicación con alguien que le interese ️  Código fuente Franklin show map Application to display a map from the MapBox library and execute events to add markers on the map ️ Show MapBox map with React ️Application to display a map from the MapBox library and execute events to add markers on the map ️  Features ️View a full screen map Place a marker at the initial position when loading the map Add a new marker when double clicking on the map  Technologies React JSTypeScriptVite JSMapBox Installation Clone the repository you need to have Git installed git clone Install dependencies of the project npm installRun the project npm run devNote For running the tests use the following command npm run test Links ️Demo of the application Here s the link to the tutorial in case you d like to take a look at it eyes View on GitHub 2022-07-01 13:39:35
Apple AppleInsider - Frontpage News Jamf launches Safe Internet for students and educators https://appleinsider.com/articles/22/07/01/jamf-launches-safe-internet-for-students-and-educators?utm_medium=rss Jamf launches Safe Internet for students and educatorsDevice management firm Jamf has launched its Jamf Safe Internet service allowing teachers to block certain sites and for students of all ages to browse safely As announced in April the Jamf Safe Internet service is available to subscribers It gives educators the ability to set all of their organization s devices with content filtering that works even when students take them home With technology now firmly embedded in the student experience Suraj Mohandas Senior Director of Education Strategy Jamf said in a statement there is a growing need for digital safety to eliminate cyberattacks and prevent students from accessing unsafe content Read more 2022-07-01 13:46:07
Apple AppleInsider - Frontpage News Daily deals July 1: eBay 4th of July sale, $120 off stainless steel Apple Watch Series 7, $50 off LG UltraFine 4K, more https://appleinsider.com/articles/22/07/01/daily-deals-july-1-ebay-4th-of-july-sale-120-off-stainless-steel-apple-watch-series-7-50-off-lg-ultrafine-4k-more?utm_medium=rss Daily deals July eBay th of July sale off stainless steel Apple Watch Series off LG UltraFine K moreIn addition to eBay s th of July sale Friday s best deals include off a digital electric smoker a AirTag wallet case a TB Seagate HDD for and much more Best deals July On a daily basis AppleInsider checks online stores to uncover discounts on products including Apple hardware mobile devices hardware upgrades smart TVs and accessories The best offers are compiled into our daily deals post for you to enjoy Read more 2022-07-01 13:13:06
Apple AppleInsider - Frontpage News M2 MacBook Pro and 15 years of iPhone on the AppleInsider Podcast https://appleinsider.com/articles/22/07/01/m2-macbook-pro-and-15-years-of-iphone-on-the-appleinsider-podcast?utm_medium=rss M MacBook Pro and years of iPhone on the AppleInsider PodcastThere s so much to look forward to in iOS and more but there s also time on this AppleInsider Podcast episode to look back so fondly at the iPhone on its th birthday Yes we ve got the new M inch MacBook Pro and are trying hard to work out why anyone would buy one On the other hand though there s the forthcoming M MacBook Air to dream about Then at least a year or two away there s the promise of TSMC manufacturing even more powerful nm processors ーand all that could bring to future Apple devices Read more 2022-07-01 13:54:24
海外TECH Engadget Ducati's first electric motorcycle is designed for MotoE racing https://www.engadget.com/ducatis-first-electric-motorcycle-will-compete-in-moto-e-and-hit-up-to-171-mph-134535639.html?src=rss Ducati x s first electric motorcycle is designed for MotoE racingDucati has unveiled not just its first electric motorcycle but a key piece in the season of MotoE e motocycle racing it announced The VL prototype has that classic Ducati look but is swathed in carbon fiber and packs a HP electric motor with a kWh battery As detailed in an announcement last year Ducati will be the exclusive supplier of all bikes used for FIM MotoE World Cup racing from It weighs in at kilograms pounds with just under half the weight for the battery ーvery heavy for a racing bike pounds more than ICE models but still pounds under the MotoE specification for It s also kg pounds less than the Energica e motocycles currently used in MotoE racing nbsp The VL can be charged to percent in just minutes and has enough range to complete the required seven laps of key GP tracks It has reportedly hit speeds of up to MPH at the Mugello MotoGP Circuit in Tuscany nbsp The e motorbike is quite a bet by and on Ducati considering it s never done one before but the company said it used its extensive racing experience to design the model At the same time it ll take racing lessons learned back to its consumer models nbsp quot At this moment the most important challenges in this field remain those related to the size weight autonomy of the batteries and the availability of the charging networks quot said Ducati R amp D director Vincenzo De Silva in a statement quot Helping the company s internal expertise to grow is already essential today to be ready when the time comes to put the first street electric Ducati into production quot 2022-07-01 13:45:35
海外TECH Engadget Meta allows select creators to post their NFTs on Facebook https://www.engadget.com/meta-nft-facebook-test-133049681.html?src=rss Meta allows select creators to post their NFTs on FacebookNon fungible tokens have arrived on Facebook Meta has confirmed to TechCrunch that it has started giving select creators in the US the power to post digital collectibles on their profiles While it s unclear if and when the feature will make its way to more users ーMeta called the release a quot slow rollout quot ーcompany CEO Mark Zuckerberg previously said that Meta was going to test NFT support on the social network Meta Product Manager Navdeep Singh has posted photos on Twitter of what NFT integration would look like on Facebook s and similar to Instagram s implementation creators will have a digital collectibles tab on their profile where they can show off their NFTs Creators will be able to post their collectibles as status updates that people can comment on and react to and clicking on them shows information on the artwork According to Decrypt Facebook will allow users to link their compatible digital wallets with the website similar to how they can do so on Instagram At the moment Facebook supports NFTs minted on Ethereum and Polygon though it will soon support Solana and Flow NFTs as well nbsp We re launching NFTs on Facebook Excited to share what I ve been working on with the world pic twitter com TaVzRanVーNavdeep Singh navdeep ua June Meta started testing NFT integration on Instagram in May promising additional related features such as allowing users to display their pieces as augmented reality stickers in Stories NFTs are perhaps a more fitting addition to Instagram than Facebook based on the platforms userbase but Meta is determined to make them a part of its products Zuckerberg wrote in the post announcing the arrival of digital collectibles on Instagram quot We re starting building for NFTs not just in our metaverse and Reality Labs work but also across our family of apps quot 2022-07-01 13:30:49
Cisco Cisco Blog Today’s high speed optical links would fail if not for this technology (Part 2) https://blogs.cisco.com/sp/todays-high-speed-optical-links-would-fail-if-not-for-this-technology-part-2 Today s high speed optical links would fail if not for this technology Part Learn about the technology that enables the latest high speed pluggable optics In part two of this two part blog post we discuss the trade offs and performance impact of forward error correction FEC on the network 2022-07-01 13:26:29
Cisco Cisco Blog Together we can make an impact: How a beach clean-up united a community https://blogs.cisco.com/csr/together-we-can-make-an-impact-how-a-beach-clean-up-united-a-community Together we can make an impact How a beach clean up united a communityCisco s Catarina Pereira shares more about her favorite beach clean up and how environmental activities can bring communities together 2022-07-01 13:00:44
海外科学 NYT > Science ‘Mango Man’ Is the Fruit’s Foremost Poet, Philosopher, Fan and Scientist https://www.nytimes.com/2022/07/01/world/asia/india-mango-kaleem-ullah-khan.html Mango Man Is the Fruit s Foremost Poet Philosopher Fan and ScientistWith types of mangos to his horticultural credit Kaleem Ullah Khan is quick to tell anyone in India and beyond about the infinite potential of the fruit and its tree including as medicine 2022-07-01 13:45:20
金融 金融庁ホームページ 人事異動(令和4年7月1日現在)を掲載しました。 https://www.fsa.go.jp/common/about/jinji/index.html 人事異動 2022-07-01 14:00:00
ニュース @日本経済新聞 電子版 日本では夫婦の5.5組に1組が不妊の検査・治療の経験を持ちます。4月から保険適用範囲が拡大され、経済的に諦めていた患者も治療に臨めるようになってきました。負担軽減のために使える制度をまとめました。 https://t.co/5drPtrGZuP https://twitter.com/nikkei/statuses/1542870700511354881 日本では夫婦の組に組が不妊の検査・治療の経験を持ちます。 2022-07-01 14:00:14
ニュース @日本経済新聞 電子版 自動車関連の会社向けにマニュアルを作るシイエム・シイは、VRやARの活用に力を入れています。タブレット端末を車にかざすと修理の手順が浮かび上がるアプリを開発しました。 ▶全編映像はこちら… https://t.co/IDc0gSoUHI https://twitter.com/nikkei/statuses/1542863116429676544 2022-07-01 13:30:06
ニュース @日本経済新聞 電子版 国内コロナ感染、新たに2万3156人 累計935万5561人 https://t.co/YwvMioaCnP https://twitter.com/nikkei/statuses/1542858627186585601 累計 2022-07-01 13:12:16
ニュース BBC News - Home Julian Assange submits High Court appeal to fight extradition https://www.bbc.co.uk/news/uk-62008245?at_medium=RSS&at_campaign=KARANGA wikileaks 2022-07-01 13:50:13
ニュース BBC News - Home Zara Aleena: Aunt remembers her as 'supportive and fearless' https://www.bbc.co.uk/news/uk-62011237?at_medium=RSS&at_campaign=KARANGA london 2022-07-01 13:26:09
ニュース BBC News - Home Watch: The moment a whale is cut free from ropes in Norwegian Sea https://www.bbc.co.uk/news/world-europe-62012430?at_medium=RSS&at_campaign=KARANGA norwegian 2022-07-01 13:26:25
ニュース BBC News - Home British Grand Prix: Valtteri Bottas top in wet first practice https://www.bbc.co.uk/sport/formula1/62013302?at_medium=RSS&at_campaign=KARANGA practice 2022-07-01 13:16:52
北海道 北海道新聞 ニトリ増収減益 円安、コスト上昇が利益圧迫 3~5月期 家具値上げ検討 https://www.hokkaido-np.co.jp/article/700779/ 増収減益 2022-07-01 22:50:53
北海道 北海道新聞 教員、メタノール直接熱す 群馬の児童4人やけど事故 https://www.hokkaido-np.co.jp/article/700824/ 群馬県沼田市 2022-07-01 22:50:00
北海道 北海道新聞 羽生「より高み目指す」 日本連盟HPでコメント https://www.hokkaido-np.co.jp/article/700821/ 日本スケート連盟 2022-07-01 22:45:00
北海道 北海道新聞 住宅地、幹線道沿い上昇 帯広市内路線価 繁華街は下落傾向 https://www.hokkaido-np.co.jp/article/700805/ 帯広市内 2022-07-01 22:25:53
北海道 北海道新聞 牛の受精卵、ドローンで配送 上士幌で実証実験開始 https://www.hokkaido-np.co.jp/article/700800/ 上士幌町 2022-07-01 22:21:39
北海道 北海道新聞 釧路町木場3年連続1位 釧根路線価 釧路駅周辺は下落 https://www.hokkaido-np.co.jp/article/700818/ 釧路町木場 2022-07-01 22:21:00
北海道 北海道新聞 似鳥昭雄ニトリHD会長「私が間違っていた」 止まらぬ円安に https://www.hokkaido-np.co.jp/article/700792/ 似鳥昭雄 2022-07-01 22:10:23
北海道 北海道新聞 滑空2.6キロ、スリルと爽快感 ジップライン営業スタート 倶知安 https://www.hokkaido-np.co.jp/article/700812/ hanazono 2022-07-01 22:11:00
北海道 北海道新聞 空知管内17人感染 新型コロナ https://www.hokkaido-np.co.jp/article/700810/ 新型コロナウイルス 2022-07-01 22:08:00
北海道 北海道新聞 広5―3巨(1日) 広島、連敗3で止める https://www.hokkaido-np.co.jp/article/700808/ 連続 2022-07-01 22:08:00
北海道 北海道新聞 十勝管内28人感染 新型コロナ https://www.hokkaido-np.co.jp/article/700807/ 十勝管内 2022-07-01 22:08:00
北海道 北海道新聞 NY円、135円前半 https://www.hokkaido-np.co.jp/article/700803/ 外国為替市場 2022-07-01 22:04:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)