Melk

Application Mobile

Afficher les posts WordPress sur google maps dans une application mobile avec REST Api, Ionic

WordPress

Indiquer coordonnées Lat et Long dans deux champs personnalisés “lat” et “lng”

Ex : lat = 43.785687 et long = 48,456778

Inclure les champs personnalisés dans REST. Dans fonctions.php :

function slug_get_post_meta_cb( $object, $field_name, $request ) {
 return get_post_meta( $object[ 'id' ], $field_name );
}
add_action( 'rest_api_init', function() {
 register_api_field( 'post',
 'lat',
 array(
 'get_callback' => 'slug_get_post_meta_cb',
 'update_callback' => 'slug_update_post_meta_cb',
 'schema' => null,
 )
 );
 register_api_field( 'post',
 'lng',
 array(
 'get_callback' => 'slug_get_post_meta_cb',
 'update_callback' => 'slug_update_post_meta_cb',
 'schema' => null,
 )
 );
});

Si les coordonnées sont dans un champ unique “lat_long” (lat_long=”43.785687,48,456778″) séparer en deux champs lorsque le post est enregistré. Dans fonctions.php :

function acf_save_lat_lng( $post_id ) {
 $value = get_post_meta( get_the_ID(), 'lat_long', true );
 list($lat, $lng) = explode(',', $value);
 update_post_meta( $post_id, 'lat', $lat );
 update_post_meta( $post_id, 'lng', $lng );
 }
 add_action('save_post', 'acf_save_lat_lng', 20);

Application

Dans index.html :

<script src="https://maps.google.com/maps/api/js"></script>

Dans controller.js :

.controller('MapsCtrl', function($scope, $ionicLoading, PostService, $http) {
var infoWindow = new google.maps.InfoWindow();
 $http({
 method: 'GET',
 dataType: 'jsonp',
 url: 'ADRESSE_DU_SITE/wp-json/wp/v2/posts',
 headers: {
 'Content-Type': 'application/json'
 }
 })
 .success(function(data) {
 $scope.data = data;

var json = $scope.data;

var map = new google.maps.Map(document.getElementById("map"), {
 center: new google.maps.LatLng(48.826048, 2.267668),
 zoom: 12,
 mapTypeId: google.maps.MapTypeId.ROADMAP
 });

for (var i = 0, length = json.length; i < length; i++) {
 var data = json[i],
 latLng = new google.maps.LatLng(data.lat[0], data.lng[0]);

var marker = new google.maps.Marker({
 position: latLng,
 map: map,
 title: data.title.rendered
 });

(function(marker, data) {

google.maps.event.addListener(marker, "click", function(e) {
 infoWindow.setContent('<a href="#/app/post/' + data.id + '">' + data.title.rendered + '</a>' + data.content.rendered);
 infoWindow.open(map, marker);
 });

})(marker, data);

}

})
 .error(function(data) {
 console.log('erreur');

});

})

Dans maps.html :

<ion-view class="maps-view">
 <ion-nav-title>
 <span>Carte</span>
 </ion-nav-title>
 <ion-content scroll="false">
 <div id="map"></div>
 </ion-content>
</ion-view>

Dans apps.js :

.state('app.maps', {
 url: "/maps",
 views: {
 'menuContent': {
 templateUrl: "views/maps.html",
 controller: 'MapsCtrl'
 }
 }
 })

 

Recommended Reads
Laisser un commentaire