Location / Map Field

It looks like the first snippet, here, attempts to mimic a file containing JSON, on the server. We shouldn’t need to do this, I don’t think, unless you want to fetch map settings later, via AJAX.

The json() field method exists so you don’t actually have to know anything about JSON— it handles the conversion for you, and provides a normal PHP associative array that you are free to use however you like. Below, I use it to fetch all the location data, but you can do it piecemeal by passing in the name of the property you want back, like $page->location()->json('lat') to get only the lat property.

Typically, when I create a map in the front-end, I do something like this:

<!-- Fetch all location properties: -->
<? $location = $page->location()->json(); ?>

<!-- Output them into data-* attributes on our map element -->
<div id="map-canvas" data-lat="<?= $location['lat'] ?>" data-lng="<?= $location['lng'] ?>"></div>

You can pick up the data-* attributes with Javascript when creating a Google Maps instance. I adapted the code below from an example on the Google Maps JS API page:

var map,
    // Find the map-canvas element in the document:
    map_element = document.getElementById('map-canvas'),
    // Grab the data-lat and data-lng attributes:
    lat = map_element.getAttribute('data-lat'),
    lng = map_element.getAttribute('data-lng');
function initialize() {
  var mapOptions = {
    zoom: 8,
    // Use our stored latitude and longitude variables when providing the center:
    center: new google.maps.LatLng(lat, lng)
  map = new google.maps.Map(map_element,

google.maps.event.addDomListener(window, 'load', initialize);

Hint: You can even capture the zoom level you set in config.php by adding another data-zoom attribute and appropriating the above code!

<div id="map-canvas" data-lat="<?= $location['lat'] ?>" data-lng="<?= $location['lng'] ?>" data-zoom="<?= c::get('place.defaults.zoom') ?>"></div>
1 Like