The wordpress mobile app lets you store gps position as option for each post. I would like to have a map that displays a point for each post. I saw a lot of questions about this, most of them are quite old. I don't know since when the mobile app lets you add your position as option for the post, but I would like to use this native function instead of external plugin. Any help?
1 Answer
The GPS position is saved on two post meta fields: geo_latitude and geo_longitude.
You can use these meta values to draw the posts as markers on a Google Maps.
For example, using Google Maps API, you could have a template like this:
<h1>Posts on map</h1>
<div id="map" style="height: 400px;"></div>
<script>
// init map with the values you need
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 1,
center: {lat: 0, lng: 0}
});
// get all posts that have meta_key geo_latitude
<?php $query = new WP_Query( array( 'meta_key' => 'geo_latitude' ) ); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php
// get latitude and longitude from post meta
$geo_latitude = get_post_meta( get_the_ID(), 'geo_latitude', true );
$geo_longitude = get_post_meta( get_the_ID(), 'geo_longitude', true );
?>
<?php if(!empty( $geo_latitude ) && !empty( $geo_longitude )): ?>
var pos = {lat: <?php echo $geo_latitude; ?>, lng: <?php echo $geo_longitude; ?>};
var marker = new google.maps.Marker({
position: pos,
map: map,
title: '<?php the_title(); ?>'
});
<?php endif; ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap">
</script>