LoginSignup
1
1

More than 3 years have passed since last update.

【ReactNative】react-native-mapsで地図上に被せてボタンを表示する

Last updated at Posted at 2020-04-19

概要

先日【ReactNative】react-native-mapsを導入するという記事を書いて、react-native-mapsを導入しました。
しかしながら、大概のアプリは地図を表示する+何かしらのUIを重ねて表示するのではないでしょうか?
例えば下の画像のように、地図の右上に検索ボタンを設置する等です。
hoge.png

今回は、react-native-mapsMapViewに独自のUIを重ねて表示させた時のコードを紹介します。

バージョン情報

"react-native": "0.61.5",
"react-native-maps": "^0.26.1",
"native-base": "^2.13.8",

コード

まずボタンのコンポーネントを作ります。
Viewのスタイルをabsoluteかつright : '0%'とすることで常に右上に来るようにします。
内部のButton側で適宜marginを取ったりして表示を調節しましょう。
複数のボタンを横並び、縦並びにさせることもできます。

ButtonView.tsx

import React from 'react';
import { StyleSheet } from 'react-native';
import { Text, View, Button, Icon } from 'native-base';

// 地図の右上に表示する用のコンポーネント(FC)
const ButtonView : React.FC<{onPressIcon : () => void}> = (props : {onPressIcon : () => void}) => {
    return (
        <View style={{position : 'absolute', right : '0%'}}>
            <Button style={{margin : 5}} onPress={props.onPressIcon} >
                <Icon type='FontAwesome5' name='search' />
            </Button>
        </View>
    );
}

export default ButtonView;

あとはButtonViewMapViewに重ねるだけです。
MapViewのスタイルをStyleSheet.absoluteFillObjectにするのを忘れずに。

MapComponent.tsx
import React from 'react';
import { StyleSheet, Alert } from 'react-native';
import MapView from 'react-native-maps';
import { Container } from 'native-base';
import ButtonView from './ButtonView';

class MapComponent extends React.PureComponent<{}> {

    constructor(props : {}) {
        super(props);
    }

    render() {
        return (
             <Container>
                <MapView style={{...StyleSheet.absoluteFillObject}} />
                <ButtonView onPressIcon={()=>{ Alert.alert("アイコンをタップしたよ!!") }} />
             </Container>
        );
    }
}

export default MapComponent;

おわりに

今回は地図右上に独自のコンポーネントを表示する例を紹介しました。
ちょっと手を加えれば、左上や下部、あるいは真ん中に表示させることも可能です。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1