Introduction to react-native-maps

Having accurate information about your users’ location is a great way to enhance the user experience. For example, you could use this data to show users what is around them, offer exclusive deals for products and services in their area, and much more. Fortunately, if you have a React application, implementing maps is a breeze using the react-native-maps library.

react-native-maps is a component system for maps that ships with platform-native code that needs to be compiled together with React Native. In this guide, we’ll demonstrate how to integrate Google Maps into your React Native application and introduce you to fundamental components such as <MapView /> and <Marker>.

Let’s get started!

Installation

The first thing you need to do is obtain the API key for configuring Google Maps on Android. Once you have the API key, include it in your AndroidManifest.xml file as the child of the <application> element.

<meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="YOUR_API_KEY"/>

Next, run the following command to install react-native-maps in your project.

yarn add react-native-maps -E

Basic use

Remove all the default code from the App.js file and import the <MapView /> component from react-native-maps.

import MapView from "react-native-maps";

Inside the component, render the <MapView /> component.

import MapView from "react-native-maps";

const App = () => {
  return (
    <MapView
      style={{ flex: 1 }}
      initialRegion={{
        latitude: 37.78825,
        longitude: -122.4324,
        latitudeDelta: 0.05,
        longitudeDelta: 0.05
      }}
    />
  );
};

export default App;

The initialRegion prop shows the region that is to be displayed on the map when the component mounts. The initialRegion value cannot be changed after it has been initialized. Don’t forget to add the style property to specify the dimensions. Otherwise, you’ll end up with a white screen. The value { flex: 1 } will ensure that the <MapView /> takes up the entire screen.

You’ll need to pass an object with the latitude, longitude, and delta values of a region to the initialRegion prop. The latitudeDelta and longitudeDelta properties specify how much the area on the map must be zoomed. To change the region, use the region prop.

Using react-native-maps with the useState hook

To change the region with the state hook, use the onRegionChangeComplete prop to set the new region into the state. The onRegionChangeComplete is a callback prop that is called only once when the region changes.

import React, { useState } from "react";

import MapView from "react-native-maps";

const App = () => {
  const [region, setRegion] = useState({
    latitude: 51.5079145,
    longitude: -0.0899163,
    latitudeDelta: 0.01,
    longitudeDelta: 0.01
  });

  return (
    <MapView
      style={{ flex: 1 }}
      region={region}
      onRegionChangeComplete={region => setRegion(region)}
    />
  );
};

export default App;

Displaying markers on the map

Start by importing Marker from react-native-maps.

import MapView, { Marker } from "react-native-maps";

Next, render the <Marker /> component as a child of <MapView />. Pass the coordinate for the marker in the coordinate prop.

import React, { useState } from "react";

import MapView, { Marker } from "react-native-maps";

const App = () => {
  const [region, setRegion] = useState({
    latitude: 51.5078788,
    longitude: -0.0877321,
    latitudeDelta: 0.009,
    longitudeDelta: 0.009
  });

  return (
    <MapView
      style={{ flex: 1 }}
      region={region}
      onRegionChangeComplete={region => setRegion(region)}
    >
      <Marker coordinate={{ latitude: 51.5078788, longitude: -0.0877321 }} />
    </MapView>
  );
};

export default App;

The marker should be visible, as shown below.

Marker on a Map

You can add n number of markers to the map and pass it as a direct child to the <MapView /> component.

Custom marker color

To change the color of the marker, use the pinColor prop.

<Marker
  coordinate={{ latitude: 52.5200066, longitude: 13.404954 }}
  pinColor="green"
/>

Custom marker image

You can also add a custom marker image by passing the image prop to the <Marker /> component.

<Marker
  coordinate={{ latitude: 52.5200066, longitude: 13.404954 }}
  image={require("./car.png")}
/>

Custom marker view

The following will display a location with a custom marker view component.

import React, { useState } from "react";
import { View, Text } from "react-native";

import MapView, { Marker } from "react-native-maps";

const CustomMarker = () => (
  <View
    style={{
      paddingVertical: 10,
      paddingHorizontal: 30,
      backgroundColor: "#007bff",
      borderColor: "#eee",
      borderRadius: 5,
      elevation: 10
    }}
  >
    <Text style={{ color: "#fff" }}>Berlin</Text>
  </View>
);

const App = () => {
  const [region, setRegion] = useState({
    latitude: 52.5200066,
    longitude: 13.404954,
    latitudeDelta: 0.005,
    longitudeDelta: 0.005
  });

  return (
    <MapView
      style={{ flex: 1 }}
      region={region}
      onRegionChangeComplete={region => setRegion(region)}
    >
      <Marker coordinate={{ latitude: 52.5200066, longitude: 13.404954 }}>
        <CustomMarker />
      </Marker>
    </MapView>
  );
};

export default App;

Styling the map

Generate the JSON object you’ll use to design the map from the Google style generator.

Next, pass the generated style object to the customMapStyle prop of the <MapView /> component.

import React, { useState } from "react";
import { View, Text } from "react-native";

import MapView, { Marker } from "react-native-maps";

const mapStyle = [
  {
    elementType: "geometry",
    stylers: [
      {
        color: "#1d2c4d"
      }
    ]
  },
  {
    elementType: "labels.text.fill",
    stylers: [
      {
        color: "#8ec3b9"
      }
    ]
  },
  // ...
  {
    featureType: "water",
    elementType: "geometry.fill",
    stylers: [
      {
        color: "#3e73fd"
      }
    ]
  },
  {
    featureType: "water",
    elementType: "labels.text.fill",
    stylers: [
      {
        color: "#4e6d70"
      }
    ]
  }
];

const CustomMarker = () => (
  <View
    style={{
      paddingVertical: 10,
      paddingHorizontal: 30,
      backgroundColor: "#fff",
      borderColor: "#eee",
      borderRadius: 5,
      elevation: 10
    }}
  >
    <Text>Berlin</Text>
  </View>
);

const App = () => {
  const [region, setRegion] = useState({
    latitude: 52.5200066,
    longitude: 13.404954,
    latitudeDelta: 0.005,
    longitudeDelta: 0.005
  });

  return (
    <MapView
      style={{ flex: 1 }}
      region={region}
      onRegionChangeComplete={region => setRegion(region)}
      customMapStyle={mapStyle}
    >
      <Marker coordinate={{ latitude: 52.5200066, longitude: 13.404954 }}>
        <CustomMarker />
      </Marker>
    </MapView>
  );
};

export default App;

You can ignore the mapStyle variable. Since it will be generated from the map style generator, you only need to paste the JSON object into your code and send it to the <MapView /> component.

Custom-Styled Map

As you can see, the map style changed from the default light theme to a customized dark theme.

Animating to a coordinate

What if you want to animate to a particular coordinate?

First, create a ref to <MapView /> using the useRef() hook.

import React, { useState, useRef, useEffect } from "react";
import { View, Text } from "react-native";

import MapView, { Marker } from "react-native-maps";

// ...

const App = () => {
  const _map = useRef(null);

  useEffect(() => {
    // ...
  }, []);

  return (
    <>
      <MapView
        style={{ flex: 1 }}
        ref={_map}
        initialRegion={{
          latitude: 52.5200066,
          longitude: 13.404954,
          latitudeDelta: 0.1,
          longitudeDelta: 0.1
        }}
      >
        <Marker coordinate={{ latitude: 52.5200066, longitude: 13.404954 }}>
          <CustomMarker />
        </Marker>
      </MapView>
    </>
  );
};

export default App;

Next, inside the useEffect() hook, use the animateCamera() function to animate the MapView region.

useEffect(() => {
  if(_map.current) {
    _map.current.animateCamera(
      {
        center: {
          latitude: 50.1109221,
          longitude: 8.6821267
        }
        zoom: 15
      },
      5000
    );
  }
}, []);

The useRef() hook returns a mutable ref object whose current property has the value of the passed argument. If the value of current property is undefined, that means the component is not yet mounted. Now you can access any of the <MapView /> methods using _map.current.

The animateCamera() method accepts an object with center, zoom, heading, and altitude properties as its argument and the animation duration in milliseconds. You can pass the region’s latitude and longitude in the center property, but unlike the initialRegion prop, you cannot give the delta values. The zoom property specifies the extent to which the region needs to be zoomed.

Adding a line to the map

You can use the <Polyline /> component from the react-native-maps library to create lines between multiple coordinates. It accepts an array of coordinates in its coordinates prop. You can also specify additional props for styling purposes, such as strokeWidth, strokeColor, etc.

Let’s create a path between Berlin and Frankfurt.

import React from "react";
import MapView, { Polyline } from "react-native-maps";

const App = () => {
  const Berlin = {
    latitude: 52.5200066,
    longitude: 13.404954
  };

  const Frankfurt = {
    latitude: 50.1109221,
    longitude: 8.6821267
  };

  return (
    <>
      <MapView
        style={{ flex: 1 }}
        initialRegion={{
          latitude: 52.5200066,
          longitude: 13.404954,
          latitudeDelta: 0.1,
          longitudeDelta: 0.1
        }}
      >
        <Polyline coordinates={[Berlin, Franfurt]} />
      </MapView>
    </>
  );
};

export default App;

Store the coordinates for the locations in their respective variables and pass them in an array to the coordinates prop of the <Polyline /> component.

If you look at the results, the line is drawn directly between these coordinates and does not take into account the actual geographical paths and roads. For that, you’ll need to establish multiple coordinates between the source and destination locations by using the Google Maps Direction API, which returns all possible routes between two places.

Create a getDirections function that accepts the coordinates in string format.

const getDirections = async (startLoc, destinationLoc) => {
  try {
    const KEY = "YOUR GOOGLE API KEY";
    let resp = await fetch(
      `https://maps.googleapis.com/maps/api/directions/json?origin=${startLoc}&destination=${destinationLoc}&key=${KEY}`
    );
    let respJson = await resp.json();
    let points = decode(respJson.routes[0].overview_polyline.points);
    console.log(points);
    let coords = points.map((point, index) => {
      return {
        latitude: point[0],
        longitude: point[1]
      };
    });
    return coords;
  } catch (error) {
    return error;
  }
};

Import the decode() function from the @mapbox/polyline library.

import { decode } from "@mapbox/polyline";

The decode() function will convert the encoded polyline points from the overview_polyline.points property into an array containing the latitude and longitude of all the coordinates.

import React, { useState, useEffect } from "react";
import { View, Text } from "react-native";
import MapView, { Polyline } from "react-native-maps";
import { decode } from "@mapbox/polyline";

const getDirections = async (startLoc, destinationLoc) => {
  try {
    const KEY = "YOUR GOOGLE API KEY";
    let resp = await fetch(
      `https://maps.googleapis.com/maps/api/directions/json?origin=${startLoc}&destination=${destinationLoc}&key=${KEY}`
    );
    let respJson = await resp.json();
    let points = decode(respJson.routes[0].overview_polyline.points);
    let coords = points.map((point, index) => {
      return {
        latitude: point[0],
        longitude: point[1]
      };
    });
    return coords;
  } catch (error) {
    return error;
  }
};

const App = () => {
  const [coords, setCoords] = useState([]);

  useEffect(() => {
    getDirections("52.5200066,13.404954", "50.1109221,8.6821267")
      .then(coords => setCoords(coords))
      .catch(err => console.log("Something went wrong"));
  }, []);

  return (
    <>
      <MapView
        style={{ flex: 1 }}
        initialRegion={{
          latitude: 52.5200066,
          longitude: 13.404954,
          latitudeDelta: 0.1,
          longitudeDelta: 0.1
        }}
      >
        {coords.length > 0 && <Polyline coordinates={coords} />}
      </MapView>
    </>
  );
};

export default App;

Conclusion

You should now have a basic understanding of how to implement maps, their benefits, and how to build features on top of the react-native-maps library. You can implement these lessons into your work to build myriad types of applications, from taxi services, to restaurant finders, to delivery apps, and much more. The react-native-maps library makes it simple to integrate maps and is an essential player in the React Native ecosystem.

Originally published by Gaurav Singhal at https://blog.logrocket.com


React Native Maps Tutorial


How to Use Google Maps in React Native - Part 1

How to Use Google Maps in React Native - Part 2

How to Use Google Maps in React Native - Part 3

#react-native #reactjs #mobile-apps

What is GEEK

Buddha Community

Introduction to react-native-maps
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms?

React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. Hire Dedicated React Native Developer from top React Native development company, HourlyDeveloper.io to design a spectacular React Native application for your business.

Consult with experts:- https://bit.ly/2A8L4vz

#hire dedicated react native developer #react native development company #react native development services #react native development #react native developer #react native

Hire Dedicated React Native Developers - WebClues Infotech

Being one of the emerging frameworks for app development the need to develop react native apps has increased over the years.

Looking for a react native developer?

Worry not! WebClues infotech offers services to Hire React Native Developers for your app development needs. We at WebClues Infotech offer a wide range of Web & Mobile App Development services based o your business or Startup requirement for Android and iOS apps.

WebClues Infotech also has a flexible method of cost calculation for hiring react native developers such as Hourly, Weekly, or Project Basis.

Want to get your app idea into reality with a react native framework?

Get in touch with us.

Hire React Native Developer Now: https://www.webcluesinfotech.com/hire-react-native-app-developer/

For inquiry: https://www.webcluesinfotech.com/contact-us/

Email: sales@webcluesinfotech.com

#hire react native developers #hire dedicated react native developers #hire react native developer #hiring a react native developer #hire freelance react native developers #hire react native developers in 1 hour

Factors affecting the cost of hiring a React Native developer in USA - TopDevelopers.co

Want to develop app using React Native? Here are the tips that will help to reduce the cost of react native app development for you.
Cost is a major factor in helping entrepreneurs take decisions about investing in developing an app and the decision to hire react native app developers in USA can prove to be fruitful in the long run. Using react native for app development ensures a wide range of benefits to your business. Understanding your business and working on the aspects to strengthen business processes through a cost-efficient mobile app will be the key to success.

#best react native development companies from the us #top react native app development companies in usa #cost of hiring a react native developer in usa #top-notch react native developer in usa #best react native developers usa #react native

How much does it cost to develop a React Native mobile app?

React Native allows developers to develop mobile apps that have compatibility with Android, iOS & other operating systems. Due to the features like Native-like functionality and single code reusability and the access of various frameworks in the market, React Native has excelled as the most suitable framework for cross-platform mobile app development.

Why Do Businesses Prefer React Native App Development?

React Native is integrated with JS library that works as the fundamental for developing the app UI. Most businesses choose for developing React Native apps just due to their cross-platform & open-source features. A few further reasons why entrepreneurs & developers choose React Native app development include:

• Lowered Expedition Time

• Simple UI

• Cross-Platform and Code Sharing

• Lesser Workforce and Resources

• Community Assistance

• In-Built Elements and Reusable Codes

• Hot Reload

• JavaScript as Programming Language

• Easy to Execute Updates

Factors That Decide Cost of React Native App Development

If you are an entrepreneur or start-up and looking for cost-effective app development, React Native is one of the ideal options available out there.

• App’s UI/UX Design

• User Authorization

• App Complexity and Functionality

• App Development Team

• App Maintenance

• App Add-ons

• App Distribution

• Location of Development Company

• App Category

React Native cost depends widely on the complexity of a project or the app requirements. The price may also vary based on business requirements. React Native app development per hour can cost from $20 and $30 per hour in India. It can vary as per different locations.

Is React Native a good choice for mobile apps development?

Yes, React Native is the best choice for mobile app development as React apps are faster to develop and it offers better quality than hybrid apps. Additionally, React Native is a mature cross-platform framework.

Best React Native App Development Agency

AppClues Infotech is a leading React Native App Development Company in USA that build robust & innovative mobile app as per your specific business needs. They have a dedicated team of designers and programmers help to make a perfect mobile app.

If you have any mobile app development project in mind get in touch with AppClues Infotech and get the best solution for your business.

#react native app development cost #react native development company #best react native development company in usa #hire react native developers #hire dedicated react native developers & programmers #hire a react native development company