Tutorials

Download View Demo

Dynamically Creating Markers with Google Maps API v3

This tutorial shows how to use AJAX to pull JSON feeds from Osmek to add custom markers. It also provides an introduction to custom fields.

First, go to Osmek and create a multi-entry section for all the markers. Under the settings page of the multi-entry section add a custom input field for the marker's coordinates (see screenshot below).

map-example add-custom-field-3

Now add some markers.

marker-example

Once you have created your section and added some content, set up a basic page that links to the javascript files and creates the container for the map. Notice we use fetch_template to display the markers outside the map for reference (see the demo), but this is just added functionality and by no means required.

index.php

<?php
    
include('Osmek.php');
    
$osmek = new Osmek('[api_key]');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <link rel="stylesheet" type="text/css" href="http://osmek.com/user_guide/assets/css/style.css" />
        <link rel="stylesheet" type="text/css" href="css/styles.css" />
        
        <script type="text/javascript" src="js/mootools-core.js"></script>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript" src="js/map.js"></script>
    </head>
    <body>
        <div id="main">
            <div id="map_canvas" class="shadow"></div>
            <div id="markers">
             <?php 
                 $template 
file_get_contents('marker-template.html');
                 echo 
$osmek->fetch_template([section_id], $template);
             
?>
            </div>
        </div>
    </body>
</html>

Create a php file to handle the data for our JSON request. Use Osmek's fetch_json function to retrieve the map information and markers. Remember use your Osmek api key and section id

markers.php

<?php
    
include('Osmek.php');
    
$osmek = new Osmek('[api_key]');
    
    echo 
$osmek->fetch_json([section_id]);
?>

Now its time to create the map. Instantiate the map object and set a default center (the script will auto center the markers later). Finally, call setMarkers() to request the JSON from markers.php. This function creates the markers by looping through the the items array of your markers section.

map.js

window.addEvent('domready', function(){
    
    var latlng = new google.maps.LatLng(30.270279746850328, -97.74001836776733);
    var myOptions = {
      zoom: 14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    setMarkers(map);
    
    
});

function setMarkers(map)
{
    var markerRequest = new Request.JSON({
        url: "markers.php", 
        onSuccess: function(data){
            var markers = [];
            data.items.each(function(item, key){
                
                //Convert coordinates to floats
                var coord = item.location.split(',');
                   var latlng = new google.maps.LatLng(coord[0].toFloat(), coord[1].toFloat());
                   marker = new google.maps.Marker({
                  position: latlng,
                  title: item.title,
                  map: map,                          
                  icon: 'http://photos.osmek.com/get/'+item.photo+'.o.png'

                  });
                  markers.push(marker);
                  var infowindow = new google.maps.InfoWindow({
                    content: 'place holder',
                    pixelOffset: new google.maps.Size(0, 25)
                });
                
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.setContent('<h3>'+item.title+'</h3>'+item.postbody);
                    infowindow.open(map,this);
                });    
                $('marker'+item.id).addEvent('click', function(e){
                    e.stop();
            
                    infowindow.setContent('<h3>'+item.title+'</h3>'+item.postbody);
                    infowindow.open(map,markers[key]);
                        
                });    
                
                
            });
            
            autoCenter(map, markers);
            
        }
    }).send();
}

function autoCenter(map, markers)
{
    //  Create a new viewpoint bound
    var bounds = new google.maps.LatLngBounds();
    //  Go through each marker...
    markers.each(function(marker, index) {
        bounds.extend(marker.position);
    });
    //  Fit these bounds to the map
    map.fitBounds(bounds);

}