From 1807a6ba5e4320c2f00ee358feb036a9fd8e268c Mon Sep 17 00:00:00 2001 From: Joni Laukka <joni.laukka.overflow@gmail.com> Date: Tue, 4 Jun 2019 14:33:03 +0300 Subject: [PATCH] Own position is shown on the map when the map component did mount. --- src/components/UserMap.js | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/components/UserMap.js b/src/components/UserMap.js index 31092dc..1a28393 100644 --- a/src/components/UserMap.js +++ b/src/components/UserMap.js @@ -2,15 +2,33 @@ import React, { Component } from 'react'; import { Map, TileLayer, Marker, Popup } from 'react-leaflet'; class UserMap extends Component { + constructor(props){ + super(props); + this.state = { + ownLat: null, + ownLng: null, + } + } + + componentDidMount(){ + this.getCurrentPosition((position) => { + if(position != null){ + this.setState({ + ownLat: position.lat, + ownLng: position.lng, + }); + } + }); + } - getCurrentPosition(){ + getCurrentPosition(callback){ if(!navigator.geolocation){ console.log("Can't get geolocation :/"); - return null; + callback(null); } else{ - navigator.geolocation.getCurrentPosition((position)=>{ - return ({ + navigator.geolocation.getCurrentPosition((position)=> { + callback({ lat: position.coords.latitude, lng: position.coords.longitude }); @@ -30,6 +48,7 @@ class UserMap extends Component { Se on perjantai, my dudes <br /> </Popup> </Marker> + {this.state.ownLat !== null && <Marker position={[this.state.ownLat, this.state.ownLng]}></Marker>} </Map> ); } -- GitLab