πŸ—ΊοΈ Exploring Maps with React Native and Mapbox πŸŒπŸ—ΊοΈ

in blurt β€’Β  last yearΒ 

Are you ready to take your React Native app to the next level by incorporating interactive maps? Mapbox is here to help! In this blog post, we'll dive into the code above to build an exciting map application that lets you switch between two different map styles with the touch of a button. πŸš€

src

πŸ’‘ What is Mapbox?

Mapbox is a powerful mapping platform that provides developers with tools to create stunning maps and location-based applications. It offers various map styles, allows customization, and supports real-time data visualization. The above code uses the Mapbox SDK for React Native to create an interactive map with user location tracking. πŸ—ΊοΈ

πŸ“¦ Setting Up

Before we begin, make sure you have set up your React Native project and installed the necessary dependencies, including '@rnmapbox/maps' and '@rnmapbox/maps'. You'll also need a Mapbox access token, which you can get by signing up on their website. This token allows you to access Mapbox services. πŸ“²

import Mapbox from '@rnmapbox/maps';
import MapboxGL from '@rnmapbox/maps';
import React, { useEffect, useState, useRef } from 'react';
import { StyleSheet, View, PermissionsAndroid, Text, Alert } from 'react-native';
import StyleJsonExample from './style-json-example.json';
import StyleJsonExample2 from './style.json';
import Bubble from './Bubble';

Mapbox.setAccessToken(
  'YOUR_TOKEN',
);

const styles = StyleSheet.create({
  map: {
    flex: 1,
  },
});

const defaultCamera = {
  centerCoordinate: [-78.54382, 40.446947],
  zoomLevel: 3,
  minZoomLevel: 3,
};

const App = props => {
  const [showAltStyle, setShowAltStyle] = useState(false);

  const onPress = () => {
    setShowAltStyle(!showAltStyle);
  };
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  useEffect(() => {
    const requestLocationPermission = async () => {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        } else {
          setErrorMsg('Permission to access location was denied');
        }
      } catch (error) {
        console.error(error);
      }
    };

    requestLocationPermission();
  }, []);
  const onUserMarkerPress = (): void => {
    Alert.alert('You pressed on the user location annotation');
  };

  const [pointInView, setPointInView] = useState(null);
  const mapRef = useRef(null);

  const onPress2 = async e => {
    const pointInView = await mapRef.current.getPointInView(
      e.geometry.coordinates,
    );
    setPointInView(pointInView);
  };

  const renderPointInView = () => {
    if (!pointInView) {
      return <Text>Touch map to see xy pixel location</Text>;
    }

    return [
      <Text key={'x'}>x: {pointInView[0]}</Text>,
      <Text key={'y'}>y: {pointInView[1]}</Text>,
    ];
  };

  return (
    <View style={{ flex: 1, backgroundColor: 'white' }}>
      <Mapbox.MapView
        styleURL={MapboxGL.StyleURL.Light}
        style={styles.map}
        ref={mapRef}
        onPress={onPress}
      >
        <Mapbox.Camera
          defaultSettings={defaultCamera}
          followZoomLevel={12}
          followUserLocation
        />
        <Mapbox.Style json={showAltStyle ? StyleJsonExample2 : StyleJsonExample} />
        <Mapbox.UserLocation onPress={onUserMarkerPress} />
      </Mapbox.MapView>
      <Bubble onPress={onPress}>
        <Text>{showAltStyle ? 'Style 2' : 'Style 1'}</Text>
        {/* {renderPointInView()} */}
      </Bubble>
    </View>
  );
};
export default App;


src

🚦 Location Permissions

The app starts by requesting permission to access the user's location using the PermissionsAndroid API from React Native. Location permissions are crucial for features like user location tracking on the map. The user will be prompted to grant permission when the app is launched. πŸ“

🎨 Styling the Map

The main functionality of this app revolves around switching between two different map styles. The 'StyleJsonExample' and 'StyleJsonExample2' files contain the JSON representation of the map styles. By default, the app starts with 'StyleJsonExample' set as the map style.

πŸ“ Getting XY Pixel Location

One cool feature demonstrated in this app is the ability to get the XY pixel location on the map when the user touches it. When the user taps on the map, the 'onPress2' function is triggered, which uses 'mapRef.current.getPointInView' to calculate the pixel location of the point where the user tapped. The XY pixel location is then displayed on the screen. ### πŸ‘‰

🎯 User Location Tracking

With Mapbox, it's easy to display and track the user's location on the map. The 'Mapbox.UserLocation' component does just that. It displays the user's location on the map and allows you to handle events when the user interacts with it. In this case, 'onUserMarkerPress' is triggered when the user presses on their location annotation. πŸ“

πŸ–±οΈ Interaction with the Map

Finally, the app includes a button wrapped in the 'Bubble' component that allows users to toggle between the two map styles. Pressing the button triggers the 'onPress' function, which toggles the 'showAltStyle' state. Depending on the 'showAltStyle' state, the app either renders 'StyleJsonExample' or 'StyleJsonExample2' as the map style.

src
That's it! With just a few lines of code, you have a fully functional map application that lets users explore different map styles and interact with their location. πŸ—Ύ

Feel free to expand on this app by adding more features from the Mapbox SDK, such as adding markers, routes, or customizing map elements. Mapbox offers a wide range of possibilities for enhancing your maps and making your location-based apps stand out. 🌟

Happy coding! πŸš€πŸŽ‰

Let us know if you have any questions or need further assistance. Happy mapping! πŸ—ΊοΈπŸ—ΊοΈπŸ—ΊοΈ

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order: Β 
Β  Β· Β last yearΒ  Β· Β 

Dear @fanhim, your content was selected manually by curators @nalexadre, @ten-years-before to receive a curation from BeBlurt πŸŽ‰

image
BeBlurt (Blurt frontend): https://beblurt.com
Β 
BeBlurt Delegation program: manual curation + 85% reward back
Β