I want to display multiple tags on my google map based on the location from my database. I am using PHP and javascript for my map. I am at lost for the moment on how I will be able to show all the locations from my database. Could anyone please help me? I would really appreciate it. Thanks in advance!
below is my current code for my map:
<?php
$hostname = 'localhost';
$dbname = 'db'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
mysql_connect("$hostname", "$username", "$password") or DIE("Connection to host is failed, perhaps the service is down!");
mysql_select_db("$dbname") or DIE("database not available");
$loc = "N1433.704483,E12100.012501";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>DLTI Locator</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 500px;"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', latitude,longitude ],
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(14.5833, 120.9667),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
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));
}
</script>
</body>
</html>
try this tutorial.. i used it to get markers from my database.. you too could do the same..
https://developers.google.com/maps/articles/phpsqlajax_v3
Related
I currently have realtime analytics php api. It has this entity named $resulting. If I do print_r($resulting); it returns for example (if only 1 user is online):
Array ( [0] => Array ( [0] => Arnhem [1] => 5.898730 [2] => 51.985104 [3] => Chrome [4] => DESKTOP [5] => / [6] => 1 ) )
Now, later on in the same file, I have the google maps javascript api.
It has markers in the form of:
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
As placeholder for now.
What I want to do, is have in the coords: section have the lat: and lng: be the appropriate values from $resulting.
Also, I want to have as many markers as there are users online.
Now, I have tried everything I can think of, but I can't get it to work.
I have tried for example:
const results = <? php echo json_encode($resulting); ?>;
let markers = [];
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
}
};
}
but then the maps won't load anymore.
I have tried looping, foreach, trying to get the lat: and lng: to update with the values returned by $resulting, but whatever I do it simply won't work.
Can anybody help me and get this working?
Thanks.
edit:
adding the index.php file as requested:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php
require_once __DIR__ . '/../google/vendor/autoload.php';
$analytics = initializeAnalytics();
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . 'MY KEY FILE LOCATION';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
/**
* 1.Create and Execute a Real Time Report
* An application can request real-time data by calling the get method on the Analytics service object.
* The method requires an ids parameter which specifies from which view (profile) to retrieve data.
* For example, the following code requests real-time data for view (profile) ID 56789.
*/
$optParams = array(
'dimensions' => 'rt:city, rt:longitude, rt:latitude, rt:browser, rt:deviceCategory, rt:pagePath');
try {
$resultsrealtime = $analytics->data_realtime->get(
'ga:MY GOOGLE CLIENT ID',
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
/**
* 2. Print out the Real-Time Data
* The components of the report can be printed out as follows:
*/
$resulting = $resultsrealtime->getRows();
function test() {
if(count($resulting == false)){
return;
}
else if(count($resulting) > 0){
foreach ($resulting as $resultingTwo => $resultingThree) {
foreach ($resultingThree as $resultingFour){
echo $resultingFour.'<br />';
}
}
} else {
echo 'No visitors';
}
}
?>
<script>
// Map options
function initMap(){
var options = {
zoom:7,
center:{lat:52.0907, lng:5.1214}
}
// New map
var map = new google.maps.Map(document.getElementById('map'), options);
// Array of markers
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
iconImage:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
// Loop through markers
for(var i = 0; i < markers.length; i++){
// add Marker
addMarker(markers[i]);
}
// Add Marker Function
function addMarker(props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
//icon:props.iconImage
});
// Check for custom icon
if(props.iconImage){
// Set icon image
marker.setIcon(props.iconImage);
}
// Check for content
if(props.content){
// Set content
// Info Window
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('mouseover', function(){
infoWindow.open(map, marker);
// Reset Info Window
setTimeout(function(){
infoWindow.open()
}, 500);
}, false);
}
}
}
</script>
<div id="data"><p><?php $test = json_encode($resulting); print_r($test);?></p></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Also, what the json_encode returns with 2 users online:
[["Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"],["Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1"]]
You should also assign the map object to the marker (assuming your map object is named map )
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
},
map: map
};
}
To help you identify the issue, it would be useful to see the rest of your javascript code for the map api, as well as the array when there's more than one user after running it though json_encode(). That said, try the following:
const results = <? php echo json_encode($resulting); ?>;
for(let i = 0; i < results.length; i++) {
let marker = new google.maps.Marker({
position: {lat: results[1], lng: results[2]},
content: '<h1>' + results[0] + </h1>,
map: map
});
}
Edit:
I don't have Composer installed in the directory I tested your code in, and I haven't worked much with the Google realtime API, but the following javascript will work given the output you listed for $resulting. You'll have to tweak things depending on where your custom icons are coming from, but that should be pretty straightforward.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php $resulting = array(array("Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"), array("Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1")); ?>
<script>
const resultingArr = <?php echo json_encode($resulting); ?>;
function initMap() {
var options = {
zoom: 7,
center: {
lat: 52.0907,
lng: 5.1214
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
function mapMarkers(props) {
const marker = new google.maps.Marker({
position: props.coords,
map: map,
icon: props.iconImage
});
const infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.addListener('mouseover', function() {
infoWindow.open(map, marker);
});
marker.addListener('mouseout', function() {
infoWindow.close();
});
}
for (let i = 0; i < resultingArr.length; i++) {
mapMarkers({
coords: {
lat: parseFloat(resultingArr[i][2]),
lng: parseFloat(resultingArr[i][1])
},
content: '<h3>' + resultingArr[i][0] + '</h3>'
})
}
};
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Hope this helps!
I'm using google maps API to make a map that retrieves data from the database and shows the corresponding markers on the map. I did this by following these instructions: https://developers.google.com/maps/articles/phpsqlajax_v3
What I'm now trying to do is create a page (called add_marker.php) that has a draggable marker so that the user can then add the new marker to the database based on the coordinates. I want to be able to see the other markers when I'm on this page. I also include the map code in all the pages so I don't want it to change drastically just for this page, so my approach is the following: Make the draggable marker invisible in all the pages except for the add_marker page by setting the icon setting to an empty string " ". Now the problem is, I can't change the icon's image so I can see it in the particular page I want it visible. I've searched quite a bit here in stackoverflow and found some solution, but none of these worked.
The error that I get is: add_marker.php:9 Uncaught Reference Error: drag_marker is not defined
(Even though I've made the marker variable global)
The code is the following:
map_code.php (This is the page that I made with the help of the link and is almost identical to that code except for some variable names. It's included in the files that use the map)
Any help would be greatly appreciated
<!DOCTYPE html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY"
type="text/javascript"></script>
<script type="text/javascript">
var drag_marker;
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.511769, 22.371699),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var content = markers[i].getAttribute("content");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var content = markers[i].getAttribute("content");
var icon = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
});
bindInfoWindow(marker, map, infoWindow, content, name);
}
});
*var uluru = {lat: 37.52, lng: 22.37};
drag_marker = new google.maps.Marker({
icon: " ",
draggable: true,
position: uluru,
map: map
});*
}
function SelectElement(valueToSelect)
{
var element = document.getElementById("markerList");
element.value = valueToSelect;
}
function bindInfoWindow(marker, map, infoWindow, html, name) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
infoWindow.setContent("<p>" + name + "<br />" +
html + "<br />");
SelectElement(name);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 99.5%; height: 40%"></div>
</body>
</html>
add_marker.php:
<html>
<head>
<title>My website</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
drag_marker.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
</script>';
</head>
<body>
<div id="container">
<div id="header">
<h1><img src="logo.png" align="center" alt="logo" style="width:300px;height:60px;"><img src="gavlab.png" align="right" alt="logo" style="width:200px;height:55px;"></h1>
</div>
<div id="content">
<div id="nav">
<h3>Πλοήγηση</h3>
<ul id="menu">
<li>Homepage</li>
<li align="left">Map</li>
<li>Admin log-in</li>
<li>info</li>
<li>Contact</li>
</ul>
</div>
<div id="main">
<h6 align="center">Map</h6>
<?php include("map_code.php"); ?>
<div align="center" id="admin_menu">
<?php
error_reporting(E_ALL & ~E_NOTICE ^ E_DEPRECATED ^ E_WARNING );
//http://www.clker.com/cliparts/e/3/F/I/0/A/google-maps-marker-for-residencelamontagne-hi.png
// icon:"http://maps.google.com/mapfiles/ms/icons/red-dot.png",
SESSION_START();
if($_SESSION['username'] == "admin"||$_SESSION['username'] == "username"){
echo '<p align="center" style="color:#8A2908"> Welcome εδώ.</p>';
$con= mysql_connect('localhost','root','');
mysql_set_charset('utf8');
mysql_select_db('qr code');
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $con);
$sql="SELECT * FROM array1";
$records=mysql_query($sql);
echo '<form id="main_form" name = "add_new_marker" action="marker_info.php" method="post">';
'</form>';
}
else echo '<p align="center" style="color:#8A2908">Please log in εδώ.</p>';
?>
</div>
</div>
</div>
<div id="footer">
Copyright © 2016 Name Here
</div>
</div>
</body>
</html>
You are attempting to use the drag_marker variable before it is defined (and probably also before it is initialized, look at the HTML/JavaScript rendered in the browser).
To deal with the timing issue, try:
google.maps.event.addDomListener(window, 'load', function() {
drag_marker.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
}):
i've been dealing with this couple of hours and i still cant figure how to do it.
my objective is to display only one marker when searching addresses close to each other.
below you have the code i use in my html in order to search for addresses, note - i'm developing a windows application that does such, in which case you might find some missing stuff to do actions by clicking buttons since this is done via .NET windows application
html code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var geocoder = new G.Geocoder();
var marker;
var markersArray = [1];
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
reading previous posts i know that if/else statement has to be used but cant get it right.
your help is very appreciated.
Leo P.
You can add a small bit of code to the beginning of your Geocode function that will remove the previous marker before setting a new one. Try this:
function geocode(address){
if (marker) {
marker.setMap(null);
}
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
Create only one marker as a global variable and change its position as needed. Like that you also save memory because you're not creating a new marker object on each request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style>
html, body {width:100%; height:100%}
</style>
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var marker;
var geocoder = new G.Geocoder();
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
// Create a single marker, (global variable), and don't give it a position just yet.
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
});
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//Position the marker
marker.setPosition(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
I am very new in HTML5 area, I am trying to make a program that will fetch the data from mysql with PHP and use geocode to transform from address to Latlng. it is a LBS program, and I was trying for 2 weeks, my question is I cannot put markers into the Google MAP, I did the locator corrected and map is loaded, but the marker cannot land on map, please help!! thank you, and I am really appreciate your help. if this code has any mistake or problem please give me generous advice, I am very new in this area, and I am trying to learn more in HTML5 Javascript, thank you and I am very appreciate your advice!!!
my code is here:
'enter code here`<?php
require_once 'Common/system_start.php';
$sql="select addr from tab_mem order by sn desc ";
$result= mysql_query($sql);
$data=mysql_fetch_assoc($result);
$row=mysql_num_rows($result);
$n = array();
for($i=0;$i<$rows;$i++)
{
$data=mysql_fetch_row($result);
$n[] = $data[0];
}
echo '<script type="text/javascript">';
echo var n = new Array("', join($n,'","'), '");';
echo '</script>';
?>
<code>
<pre>
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0,user-scalable=no"/>
<!-- Google Maps -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js? `enter code here`sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js">
</script>
<!-- program main -->
<script type="text/javascript">
var iterator=0;
markers=n;
var a=n.length;
function load() {
var map_div = document.getElementById("map_div");
//initial locator
navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 `enter code here`});
// decide location
function onSuccess(position){
//fetching latlng from GPS
var latlng = new google.maps.LatLng(position.coords.latitude,
`position.coords.longitude);
// display map
var gmap = new google.maps.Map(
map_div, {
zoom:16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//drop the marker
function drop() {
for (var i = 0; i < a; i++) {
setTimeout(function() {
}, i * 200);
}
}
//decode address to latlng
//pass address data from PHP
for(var i in n){
var address=n;
geocoder=new google.maps.Geocoder();
geocoder.geocode({'address':address},function(results,status){
if(status==google.maps.GeocoderStatus.OK){
//alert("AAA");
address=results(i).geometry.location;
function addMarker() { markers.push(new google.maps.Marker({
postion:results(i).geometry.location,
map:gmap,
animation:google.map.animation.DROP
//iterater++;
}));
//itertor++;
}
//markerNearBy.setMap(map);
}else{
alert("Geocode was not sucessful for the following reason:"+status);
}
});
}
}
}
function onError(error) {
alert('code: '+ error.code+ '\n'
+'message: ' + error.message + '\n');
}
</script>
</head>
<body onLoad="load()">
<!-- Map Display place -->
<div id="map_div" style="width:320px; height:480px;"></div>
</body>
</html>
<code>
Your code doesn't look well-formed. You have the "addMarker" function defined inside your "for" loop. Also, it's not getting called anywhere.
Take a look at the sample code Google provides for working with markers and overlays and try to emulate it. The sample only uses one marker, but you can simply iterate through your results. You've got the right intentions by adding your Marker objects to an array, and setting your map object to the map property of the Marker, but you will need to format/restructure your code first or it will not work.
Sample code:
https://developers.google.com/maps/documentation/javascript/overlays#RemovingOverlays
I'm trying to make a small application that takes a city & state and geocodes that address to a lat/long location. Right now I am utilizing Google Map's API, ColdFusion, and SQL Server. Basically the city and state fields are in a database table and I want to take those locations and get marker put on a Google Map showing where they are.
This is my code to do the geocoding, and viewing the source of the page shows that it is correctly looping through my query and placing a location ("Omaha, NE") in the address field, but no marker, or map for that matter, is showing up on the page:
function codeAddress() {
<cfloop query="GetLocations">
var address = document.getElementById(<cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>).value;
if (geocoder) {
geocoder.geocode( {<cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: <cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</cfloop> }
And here is the code to initialize the map:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(42.4167,-90.4290);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Test"
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
I do have a map working that uses lat/long that was hard coded into the database table, but I want to be able to just use the city/state and convert that to a lat/long. Any suggestions or direction? Storing the lat/long in the database is also possible, but I don't know how to do that within SQL.
You may want to consider the following example:
Using the V2 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Geocoding Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
// Prepare this list from ColdFusion
var locations = [
'New York, NY',
'Los Angeles, CA',
'Chicago, IL',
'Houston, TX',
'Phoenix, AZ'
];
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder();
var index = 0;
var geocoderFunction = function () {
geocoder.getLatLng(locations[index], function (point) {
if (point) {
map.addOverlay(new GMarker(point));
}
// Call the geocoder with a 100ms delay
index++;
if (locations.length > index) {
setTimeout(geocoderFunction, 100);
}
});
}
map.setCenter(new GLatLng(38.00, -100.00), 3);
// Launch the geocoding process
geocoderFunction();
}
</script>
</body>
</html>
Using the V3 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Geocoding Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
// Prepare this list from ColdFusion
var locations = [
'New York, NY',
'Los Angeles, CA',
'Chicago, IL',
'Houston, TX',
'Phoenix, AZ'
];
var mapOpt = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: new google.maps.LatLng(38.00, -100.00),
zoom: 3
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOpt);
var geocoder = new google.maps.Geocoder();
var index = 0;
var geocoderFunction = function () {
geocoder.geocode({ 'address': locations[index] }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
// Call the geocoder with a 100ms delay
index++;
if (locations.length > index) {
setTimeout(geocoderFunction, 100);
}
});
}
// Launch the geocoding process
geocoderFunction();
</script>
</body>
</html>
All you need to do is to render the JavaScript array locations from ColdFusion, instead of using the hardcoded one in the example.
Screenshot from the above example:
You need to actually add the marker to the map using the addOverlay method:
var point = new GLatLng(...);
map.addOverlay(new GMarker(point));
You can also add instances of the Marker class to your map:
map.addOverlay(marker);
See the Map Overlays docs:
http://code.google.com/apis/maps/documentation/javascript/v2/overlays.html