Vue Nativeを使ってアプリにマップを表示させてマーカーを設置
Vue Native はReact Nativeとexpoをラップしているので何も考えずともマップを使うことができます!!
もし環境構築が済んでいない方は、こちらでHello Worldまでのチュートリアルがあるので、環境を整えておいて下さい。
どんなマップを使うことができる?
expoで用意されているものが、iOSではApple Maps、AndroidではGoogle Mapsを表示させるコンポーネントなので、iOSではApple Maps、AndroidではGoogle Mapsを表示することになります。
また、最近Google Maps Platformの料金体系が変わりちょっと複雑になりましたが、モバイルのGoogleMapの利用に関しては静的・動的マップの読み込みはまだ無料なので心配いりません。モバイルには優しいGoogle先生
早速やっていきましょう!
実装
早速やっていきましょう!
まずは表示部分
<template>
<view class="container">
<map-view class="container"
:initial-region="coordinates"
/>
</view>
</template>
スクリプト・スタイル部分
<script>
import { MapView } from "expo";
export default {
data: function() {
return {
coordinates: {
latitude: 45.52220671242907,
longitude: -122.6653281029795,
latitudeDelta: 0.03,
longitudeDelta: 0.03
}
};
},
components: {
MapView
}
};
</script>
<style>
.container {
flex: 1;
}
</style>
たったこれだけでマップを表示することができます!とっても簡単
さらにマーカーを追加していきます。
テンプレート部分を以下のように書き換えてください。
<template>
<view class="container">
<map-view
ref="map"
:style="{ flex: 1, }"
:initialRegion="coordinates"
>
<view v-for="(marker, markerIndex) in markers">
<map-view:marker
:key="markerIndex"
:coordinate="marker.coordinate"
:title="marker.title"
:description="marker.description"
></map-view:marker>
</view>
</map-view>
</view>
</template>
スクリプト部分を以下のように書き換えてください。
<script>
import { MapView } from "expo";
export default {
components: {
MapView
},
data: function() {
return {
markers: [
{
coordinate: {
latitude: 45.524548,
longitude: -122.6749817,
},
title: "Best Place",
description: "This is the best place in Portland",
},
{
coordinate: {
latitude: 45.524698,
longitude: -122.6655507,
},
title: "Second Best Place",
description: "This is the second best place in Portland",
},
{
coordinate: {
latitude: 45.5230786,
longitude: -122.6701034,
},
title: "Third Best Place",
description: "This is the third best place in Portland",
},
{
coordinate: {
latitude: 45.521016,
longitude: -122.6561917,
},
title: "Fourth Best Place",
description: "This is the fourth best place in Portland",
},
],
coordinates: {
latitude: 45.52220671242907,
longitude: -122.6653281029795,
latitudeDelta: 0.03,
longitudeDelta: 0.03
},
};
},
};
</script>
マーカーが表示されました!
さらにマーカーをクリックすると、titleとdescriptionが現れます。
これで終わりです。とっても簡単でしたね。ここからは解説を行います。
解説
expoのMapViewを読み込みます。iOSではApple Map,AndroidではGoogle Mapが表示されます。今回はシミュレーターがiOSなのでApple Mapが表示されます。
各値の説明
initialRegionはマップをロードするタイミングで表示される範囲の設定です
latitude,longtitude,latitudeDelta,longtitudeDeltaを設定してください。
latitude:緯度
longtitude:経度
latitudeDelta:緯度方向の表示範囲
longtitudeDelta:経度方向の表示範囲
latitudeDeltaとlongtitudeDeltaは拡大倍率の設定です。
title:マーカーの上に表示されるタイトル
description:マーカーの上に表示される説明
マーカーはlatitude,longtitudeを設定する必要があります。また、マーカーはピンではなく好きなものにカスタムすることも可能です。
スタイル
マップは高さを指定しないと表示されないので注意してください。
flex:1というのはReact Nativeのプロパティなのですが、ちょっと独特で、簡単に説明すると、要素内の割合を決める値だと思ってください。このプロパティは別記事で解説します。
まとめ
Vue Nativeで簡単にマップを設置することができました。