The Google Maps Javascript API is used to integrate maps on web pages. The new Google Maps API Version 3 is designed to be faster and more applicable to mobile devices, as well as traditional desktop browser applications.
Today, lets see how we can integrate Google Map API V3 with a ColdFusion website / application and make it interactive.
Simple code to integrate a Google Map on ColdFusion website (in fact, any HTML page):
map.cfm
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=SET_TO_TRUE_OR_FALSE"></script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onUnload="initialize();">
<div id="map-canvas"/>
</body>
</html>
Make it interactive:
You can also show the markers on Google map to point locations that you would like to indicate. Obviously, on a dynamic ColdFusion website / application, we would to show the markers based on the location results from your database. But, sending all the data (locations) to Google Map would sometimes cause troubles when it comes to large data. The map loads really slow and might even make the page unresponsive. How could we handle this situation? Here are some tips:
1) Show only the results that fall into the viewport or define the boundaries.
2) Fetch and reload the results/markers upon zooming or navigating/panning by capturing and sending the map boundaries (min & max latitudes and longitudes). Here is a sample on how you would do it.
google.maps.event.addListener(map, 'zoom_changed', onClickCallback); //listen to zoom event and call function to reload markers
google.maps.event.addListener(map, 'drag', onClickCallback); //listen to drag/pan event and call function to reload markers
function onClickCallback() {
clearOverlays();
var southWestLat = map.getBounds().getSouthWest().lat();
var southWestLng = map.getBounds().getSouthWest().lng();
var northEastLat = map.getBounds().getNorthEast().lat();
var northEastLng = map.getBounds().getNorthEast().lng();
var minLat = map.getBounds().getSouthWest().lat();
var maxLat = map.getBounds().getNorthEast().lat();
var minLng = map.getBounds().getSouthWest().lng();
var maxLng = map.getBounds().getNorthEast().lng();
$.ajax({
type: "POST",
url: "markers.cfm?minlat="+minLat+"&maxlat="+maxLat+"&minlng="+minLng+"&maxlng="+maxLng,
dataType: "json",
data: ({'southWestLat' : southWestLat , 'southWestLng' : southWestLng , 'northEastLat' : northEastLat , 'northEastLng' : northEastLng}),
success: function(json){
if (json.Locations.length > 0) {
var bounds = new google.maps.LatLngBounds();
var marker = [];
for (var i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];
var LatLngbounds = new google.maps.LatLng(location.latitude, location.longitude);
var image = new google.maps.MarkerImage('/images/custom-marker.png');
marker[i] = new google.maps.Marker({
position: new google.maps.LatLng(location.latitude, location.longitude),
map:map,
icon:image,
SearchName:location.commsearchname,
County:location.county,
State:location.state
});
markersArray.push(marker[i]);
google.maps.event.addListener(marker[i], 'click',
function(){
infowindow.close();
infowindow.setContent('<table><tr><td>'+this.SearchName+'</td></tr></table>');
infowindow.open(map, this);
}
)
bounds.extend(LatLngbounds);
}
map.fitBounds(bounds);
if (viewportOverlay != null) {
viewportOverlay.setMap(null);
}
viewportOverlay = new google.maps.Rectangle({
'bounds': bounds,
'strokeColor': '#0000ff',
'strokeOpacity': 1.0,
'strokeWeight': 2.0,
'fillOpacity': 0.0
});
viewportOverlay.setMap(map);
}
}
});
}
This way you can load and point any number of locations dynamically without having to worry about slowing down the page.
Populate address based on the user location using ColdFusion components
Display nearby address based on user location using google map with ColdFusion
1. First, we need to display map with default map location
Ex:
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 20.5937, lng: 78.9629},
zoom: 5
});
2. Get user’s location lat and lng values using geolocation object called navigator.geolocation()
navigator.geolocation.getCurrentPosition(function(position) {
var UserLocation = {
info: '<strong>This is User Location</strong><br>',
lat: position.coords.latitude,
lon: position.coords.longitude
};
var locations = [
[ UserLocation.info, UserLocation.lat, UserLocation.lon,0],
];
});
3. Pass the user’s location to CFC or ColdFusion component and get the surrounding address from the DB in JSON return format.
$.ajax({
url:'cfcs/Maps.cfc?method=getSurroundingAddr',
data: { "Latitude": UserLocation.lat, "Longitude": UserLocation.lon },
success: function(response) {
var obj = JSON.parse(response);
,
error: function(response) {
console.log('Error' + response)}
});
Return Data JSON Looks like this:
var jsondata = '{"Surroundinglocations":[{"location":"Kukatpally","lat":"17.4948", "lon":"78.3996"},{"location":"JubileeHills","lat":"17.4325", "lon":"78.4070"},{"location":"Khairtabad","lat":"17.4151", "lon":"78.4648" },{"location":"Secunderabad","lat":"17.4399", "lon":"78.4983"},{"location":"Kondapur","lat":"17.4622", "lon":"78.3568"}]}'
var obj = JSON.parse(response);
4. Loop the JSON object and populate those address on the google map with info window.
for(var key in obj.Surroundinglocations) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(obj.Surroundinglocations[key].lat, obj.Surroundinglocations[key].lon),
map: map
});
}
Hope this helps. If you need any help, please feel free to contact us.
By the way, the Google Maps API V2 is now deprecated and it is time to upgrade to Google Maps API V3. Here is the official note from Google:
The Google Maps Javascript API Version 3 is now the official Javascript API. Version 2 of this API has been officially deprecated as per our deprecation policy. We encourage you to migrate your code to this newly updated and enhanced version!
Reference(s): Google Maps JavaScript API v3 Documentation