chaser7016
chaser7016

Reputation: 595

Use JSON data from a URL to show Google Map Markers - how?

The code below display map markers on a Google map, but each location lat and long is hard coded into the JS file. What's the best way to go about pulling the data from a URL instead? Please note the script below also allows the user to click on a text link within the html and in doing so highlight a point on the map.

var stationList=[
	{"latlng":[37.7029,-121.9335],name:"Dublin, CA"},
	{"latlng":[37.6958,-121.9255],name:"Pleasanton CA"},
	{"latlng":[37.6931,-121.9262],name:"Pleasanton CA"}
]

;var infoWnd,mapCanvas;

function initialize(){
	var mapDiv=document.getElementById("map_canvas");
	mapCanvas=new google.maps.Map(mapDiv);
	mapCanvas.setMapTypeId(google.maps.MapTypeId.ROADMAP);
	
	infoWnd=new google.maps.InfoWindow();
	
	var bounds=new google.maps.LatLngBounds();
	
	var station,i,latlng;
	for(i in stationList){station=stationList[i];
		latlng=new google.maps.LatLng(station.latlng[0],station.latlng[1]);
		bounds.extend(latlng);
		var marker=createMarker(mapCanvas,latlng,station.name);
		createMarkerButton(marker);
	}

	mapCanvas.fitBounds(bounds)
	;}

function createMarker(map,latlng,title){
	var marker=new google.maps.Marker({position:latlng,map:map,title:title});
	
	google.maps.event.addListener(marker,"click",function(){infoWnd.setContent("<strong>"+title+"</title>");
	infoWnd.open(map,marker);});
	
	return marker;
}

function createMarkerButton(marker){
	var ul=document.getElementById("marker_list");
	var li=document.createElement("li");
	var title=marker.getTitle();li.innerHTML=title;ul.appendChild(li);
	google.maps.event.addDomListener(li,"click",function(){google.maps.event.trigger(marker,"click");});
}

google.maps.event.addDomListener(window,"load",initialize);
#map_canvas {
    width: 70%;
    padding-bottom: 40%;
    float: left;
 }
ul#marker_list {
    float: left;
    width: 20%;
    background: #f9f9f9;
    border: 1px solid #888;
    margin: 0 0 0 5px;
    padding: 0;
  
  }
ul#marker_list li {
    padding: 5px;
    list-style-type: none;
    color: #444;
    border-bottom: 1px solid  #888;
  }
<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<div id="map_canvas"></div>
<ul id="marker_list"></ul>
	

Upvotes: 1

Views: 2827

Answers (3)

chaser7016
chaser7016

Reputation: 595

I figured it out and in Javascript. Hope this helps other newbies too!

// Setup your globals
var locations_data;
var infowindow = new google.maps.InfoWindow();
var map;
var marker, i;
var xhr = new XMLHttpRequest();


// Define your global functions
function renderData(data) {
    var html = data.pois.slice(0,3).reduce(function (frag, item) {
        frag.appendChild(pios(item));
        return frag;
    }, document.createDocumentFragment());
    document.getElementById('locations').appendChild(html);
}

function pios(item) {
    var p = document.createElement('pre');
    p.id = item.id;
    p.textContent = item.address_1 + '\n' + item.city + ' ' + item.region + ' ' + item.postal_code;
    return p;	
}

function setup_map() {
	var avg_lat = 0;
	var avg_long = 0;
	var locations = [];

	for (var i = 0; i < 3; i += 1) {
		locations.push([
			locations_data.pois[i]["address_1"],
			locations_data.pois[i]["latitude"],
			locations_data.pois[i]["longitude"],
		]);

		avg_lat += locations[i][1];
		avg_long += locations[i][2];
	}

	avg_lat /= 3;
	avg_long /= 3;

	map = new google.maps.Map(document.getElementById('map-canvas'), {
		zoom: 12,
		center: new google.maps.LatLng(avg_lat, avg_long),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});

	for (i = 0; i < locations.length; i++) {
		marker = new google.maps.Marker({
			position: new google.maps.LatLng(locations[i][1], locations[i][2]),
			map: map
		});

		google.maps.event.addListener(marker, 'click', (function (marker, i) {
			return function () {
				infowindow.setContent(locations[i][0]);
				infowindow.open(map, marker);
			}
		})(marker, i));
	}
}


// Now configure the callback (handler) for your request.
xhr.onreadystatechange = function() {
	if (xhr.readyState == 4 && xhr.status == 200) {
		locations_data = JSON.parse(xhr.responseText);

		renderData(locations_data);
		setup_map();
	}
}


// Send the XHR
xhr.open('GET', 'http://your-URL-here.com', true);

google.maps.event.addDomListener(window, 'load', function() {
	xhr.send();
});

Upvotes: 0

The Busy Wizard
The Busy Wizard

Reputation: 1166

If you're trying to do it entirely in JavaScript and the URL that you're pulling it from is under the same domain as your page is being served from, then you can just use an XHR to load the JSON in (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest), but if it's not under the same domain, then the server serving the JSON will need to be setup to allow the cross-domain request (http://www.html5rocks.com/en/tutorials/cors/). If you control the server, then that's easy, but if you don't then you'll have to either use something server-side to fetch it for you (or a simple proxy url on your own server would work), or use something like Flash in the browser to do it, but I can't in any way recommend Flash.

Upvotes: 1

Jacob van Eijk
Jacob van Eijk

Reputation: 21

I'm assuming you can use php.

So if you can use php, you can read the content from a URL (the JSON) into a variable.

$json = file_get_contents('http://mappie.com/api/json');
$json_decoded = json_decode($json, true);

Now you can load the JSON data into an array in javascript like this.

var stationList = [
<?php
     echo '{"latlng":[' . $json_decoded["lat"] . ',' . $json_decoded["lon"] . '],name:"' . $json_decoded["name"] . '"}'
?>
];

You can use a foreach loop to loop trought the JSON and echo multiple locations.

Upvotes: 1

Related Questions