In previous lessons, featured listing data was collected through the IDX Broker API. This lesson expands on that concept by using the API response to generate map pins dynamically with JavaScript and display them on a map using Leaflet.
If you have not completed the featured listings API lesson yet, you may want to review that first.
This example uses:
- PHP
- IDX Broker API
- JavaScript
- Leaflet.js
- Stored API responses
You may also use other mapping solutions such as:
- Google Maps
- Bing Maps
Leaflet Documentation
Leaflet Quick Start Guide:
http://leafletjs.com/examples/quick-start.html
Step 1: Create the Map Page
Create a file named:
index.php
This file will:
- Load the Leaflet CSS and JavaScript libraries
- Create the map container
- Load stored map pin data from a text file
- Render listing markers on the map
Example index.php
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
</head>
<body>
<?php
echo '<h1>Make a map</h1>';
?>
<div id="mapid" style="width: 600px; height: 400px"></div>
<script>
var mymap = L.map('mapid').setView([25.79402, -80.2783], 11);
L.tileLayer(
'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw',
{
maxZoom: 18,
attribution:
'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);
<?php echo file_get_contents('IDX_API/featured_listings.txt'); ?>
var popup = L.popup();
</script>
</body>
</html>
Step 2: Retrieve Featured Listings
Next, create a PHP file that:
- Calls the IDX Broker Featured Listings API
- Loops through returned listings
- Generates Leaflet marker JavaScript
- Saves the marker code into a text file
The map page will later load this generated marker data.
Expected Leaflet Marker Format
Leaflet markers are typically structured like this:
L.marker([51.5, -0.09]).addTo(mymap)
.bindPopup("<b>Hello world!</b><br />I am a popup.")
.openPopup();
The script below dynamically replaces the latitude, longitude, image, address, and price values with data returned from the IDX Broker API.
Marker Loop Example
// Loop through returned properties
foreach ($response as $key => $value) {
// Ignore listings without longitude data
if($value["longitude"] == '0.000000000000'){
$marker = '';
}
else{
// Build popup content
$prop_bubble =
'<img src=\''.$value["image"][0]["url"].'\' width=100px>
<div id=\'address\'>'.$value["address"].'</div>
<div>'.$value["listingPrice"].'</div>';
// Build Leaflet marker JavaScript
$marker =
'L.marker(['.$value["latitude"].', '.$value["longitude"].'])
.addTo(mymap)
.bindPopup("'.$prop_bubble.'");';
// Store all markers
$markers = $markers.$marker;
}
}
// Save generated markers
file_put_contents($file, $markers);
Complete featured.php Example
<?php
// IDX Broker API key
$api_key = 'YourAPIKey';
// File to store marker data
$file = 'featured_listings.txt';
// Access URL and request method
$url = 'https://api.idxbroker.com/clients/featured';
$method = 'GET';
// Headers
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'accesskey: '.$api_key,
'outputtype: json'
);
// Set up cURL
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
// Execute request
$response = curl_exec($handle);
// Store HTTP response code
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($code >= 200 || $code < 300)
$response = json_decode($response, true);
else
$error = $code;
// Variable for all markers
$markers = '';
// Clear storage file
file_put_contents($file, $markers);
// Loop through returned properties
foreach ($response as $key => $value) {
// Ignore listings without longitude data
if($value["longitude"] == '0.000000000000'){
$marker = '';
}
else{
// Build popup content
$prop_bubble =
'<img src=\''.$value["image"][0]["url"].'\' width=100px>
<div id=\'address\'>'.$value["address"].'</div>
<div>'.$value["listingPrice"].'</div>';
// Build marker JavaScript
$marker =
'L.marker(['.$value["latitude"].', '.$value["longitude"].'])
.addTo(mymap)
.bindPopup("'.$prop_bubble.'");';
// Store markers
$markers = $markers.$marker;
}
}
// Save markers to file
file_put_contents($file, $markers);
?>
Final Setup
Once both files are in place:
- Running
featured.phpupdates the stored map marker data - Loading
index.phpdisplays the map and pins
To automate updates, you can configure a cron job on your hosting environment to run featured.php periodically.
This creates a fully custom featured listings map powered by the IDX Broker API.