I am trying to display multiple markers on Google maps using data (lat and lng) from a MySQL database. When I run a foreach loop to return these markers on the map, it returns only the last row. What might be the problem?
<?php
require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<?php foreach ($data as $key) {
echo $key['lat'];
?>
<script>
function initMap() {
var uluru = {lat: <?php echo $key['lat']; ?>, lng: <?php echo $key['lng']; ?>};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
var contentString = '<?php echo $key['address']; ?>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
title: 'Uluru (Address)'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
<?php } ?>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap">
</script>
</body>
</html>
It will be very easy to fetch all the lat and long.
require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
foreach ($data as $key)
$locations[]=array( 'name'=>'Location Name', 'lat'=>$key['lat'], 'lng'=>$key['lng'] );
}
/* Convert data to json */
$markers = json_encode( $locations );
Then set the google map markers using the php variable markers.
<script type='text/javascript'>
<?php
echo "var markers=$markers;\n";
?>
function initMap() {
var latlng = new google.maps.LatLng(-33.92, 151.25); // default location
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('map'),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
var json=JSON.parse( markers );
for( var o in json ){
lat = json[ o ].lat;
lng=json[ o ].lng;
name=json[ o ].name;
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
name:name,
map: map
});
google.maps.event.addListener( marker, 'click', function(e){
infowindow.setContent( this.name );
infowindow.open( map, this );
}.bind( marker ) );
}
}
Overall code will be :
require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
foreach ($data as $key)
$locations[]=array( 'name'=>'Location Name', 'lat'=>$key['lat'], 'lng'=>$key['lng'] );
}
/* Convert data to json */
$markers = json_encode( $locations );
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script type='text/javascript'>
<?php
echo "var markers=$markers;\n";
?>
function initMap() {
var latlng = new google.maps.LatLng(-33.92, 151.25); // default location
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('map'),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
var json=JSON.parse( markers );
for( var o in json ){
lat = json[ o ].lat;
lng=json[ o ].lng;
name=json[ o ].name;
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
name:name,
map: map
});
google.maps.event.addListener( marker, 'click', function(e){
infowindow.setContent( this.name );
infowindow.open( map, this );
}.bind( marker ) );
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap">
</script>
</body>
</html>
Related
I'm trying to load marker from database but those markers doesn't loaded. However if I try to load manually it's working.
my view view_file.php
var map;
function initialize(lt,lg) {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(lt, lg),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
<?php foreach ($position as $row) { ?>
$lat = $row['lat'];
$longi = $row['longi'];
var latLng = new google.maps.LatLng($lat,$longi);
new google.maps.Marker({
position: latLng,
map: map
})
<?php } ?>
}
</script>
</head>
<body onload="initialize(-0.165343, 113.930935)">
<div id="map-canvas" style="width: 100%; height: 600px"></div>
my controller map.php
public function __construct(){
parent::__construct();
$this->load->model('maps');
}
function index(){
$data['position'] = $this->maps->marker();
$this->load->view('include/header');
$this->load->view('view_file', $data);
$this->load->view('include/footer');
}
my model maps.php
function marker(){
$post = $this->db->get('koor');
return $post->result();
}
This code below is works (entered coordinate manually). controller are same like above.
var map;
function initialize(lt,lg) {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(lt, lg),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marker(-0.735467, 110.521677);
marker(1.549480, 116.124705);
marker(-2.558367, 115.179880);
}
function marker(lt,lg){
var latLng = new google.maps.LatLng(lt,lg);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
</script>
</head>
<body onload="initialize(-0.165343, 113.930935)">
<div id="map-canvas" style="width: 100%; height: 600px"></div>
I've tried to modified my code, searched similiar problem but nothing works, this is last shape of my code.
UPDATE
I've already solve this
var map;
function initialize() {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(-0.165343, 113.930935),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var lat, longi, marker;
<?php foreach ($position as $row) { ?>
lat = <?php echo $row->lat ?>,
longi = <?php echo $row->longi ?>,
marker = new google.maps.LatLng(lat,longi);
new google.maps.Marker({
position: marker,
map: map
});
<?php } ?>
}
Your error:
$lat = $row['lat'];
$longi = $row['longi'];
This is showing up in the javascript.
Make sure that it is going to be executed in php and not javascript.
The right code:
<?php
$lat = $row['lat'];
$longi = $row['longi'];
?>
var map;
function initialize(lt,lg) {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(lt, lg),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var lat, longi;
<?php foreach ($position as $row) { ?>
lat = <?= $row->lat ?>;
longi = <?= $row->longi ?>;
marker(lat, longi);
<?php } ?>
}
function marker(lt,lg){
var latLng = new google.maps.LatLng(lt,lg);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
</script>
</head>
<body onload="initialize(-0.165343, 113.930935)">
<div id="map-canvas" style="width: 100%; height: 600px"></div>
My index.php file is shown below. In which I want to show a map and multiple marker on it using json object. This code is only for one marker. Could u please tell me how can be this code modify for multiple markers and how can i access json object in $.ajax()??
<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var latlng = {lat: 31.566470, lng: 74.297723};
var marker;
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
map: map // replaces marker.setMap(map);
});
// now let's set a time interval, let's say every 3 seconds we check the position
setInterval(
function() {
// we make an AJAX call
$.ajax({
dataType: 'JSON', // this means the result (the echo) of the server will be readable as a javascript object
url: 'final.php',
success: function(data) {
// this is the return of the AJAX call. We can use data as a javascript object
console.log(data);
// now we change the position of the marker
marker.setPosition({lat: Number(data.lat), lng: Number(data.lng)});
},
error(error) {
console.log(error);
}
})
}
, 3000
);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
and it is my final.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','1234');
define('DB','coordinates');
$con = mysqli_connect(HOST,USER,PASS,DB);
$arr=[];
for($x=1; $x<=3; $x++){
$query = "SELECT id, longitude, latitude FROM data WHERE bus_id= ".$x." ORDER BY id DESC limit 1" ;
$qry_result = mysqli_query($con,$query);// or die(mysqli_error());
// Insert a new row in the table for each person returned
while($row = mysqli_fetch_array($qry_result)) {
$longitude = $row['longitude'];
$latitude = $row['latitude'];
array_push($arr, [
'lat'=>$longitude,
'lng'=>$latitude,
//'recs'=>$recs
]);
}
}
$record= json_encode($arr);
echo $record;
?>
this is my json object
[{"lat":"74.348047","lng":"31.569907"},{"lat":"74.307826","lng":"31.573289"},{"lat":"74.330023","lng":"31.558144"}]
The following is not tested but I think it should work. There is a function addmarker which you call in a loop to process all data returned from the ajax call. If this gets called every few seconds you also need to clear old markers from the map - hence using an array to store references to each new marker.
I found a syntax error in original code relating to the error handler - not sure if I have corrected in the right way as I do not use jQuery ~ looks ok though.
<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var latlng = { lat: 31.566470, lng: 74.297723 };
var marker;
var map;/* make the map available in all scopes */
var markers=[];/* container to store references to newly added markers */
function addmarker(map, lat, lng, title ){
/* add new marker */
marker = new google.maps.Marker({
position:{ lat:lat,lng:lng },
title:title,
draggable:true,
map:map
});
/*marker.setMap( map );*/
/* store reference */
markers.push( marker );
}
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
map: map // replaces marker.setMap(map);
});
setInterval(
function() {
$.ajax({
dataType: 'JSON',
url: 'ajax.php',
success: function(data) {
/* clear old markers */
markers.forEach( function( e,i,a ){
e.setMap( null );
});
for( var o in data ){
var lat=Number(data[o].lat);
var lng=Number(data[o].lng);
/* Watch the console, see what you get here */
console.log( 'lat:%s, lng:%s',lat,lng );
addmarker.call( this, map, lat, lng, 'Hello World - a title!' );
}
},
error: function( err ){
console.log( err );
}
})
}, 3000 );
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
The full code I used in testing
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql="select
`location_name` as 'title',
`location_map_centre_Latitude` as 'lat',
`location_map_centre_Longitude` as 'lng'
from `maps`
where `countryid`=171
order by rand()
limit 10";
$res=$conn->query( $sql );
if( $res ){
$json=array();
while( $rs=$res->fetch_object() ){
$json[]=array( 'title'=>$rs->title, 'lat'=>$rs->lat, 'lng'=>$rs->lng );
}
header('Content-Type: application/json');
echo json_encode( $json );
}
$conn->close();
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>/* initial lat/lng is in Scotland, near Forfar */
var latlng = { lat: 56.61543329027024, lng: -2.9266123065796137 };
var marker;
var map;
var markers=[];/* container to store references to newly added markers */
function addmarker(map, lat, lng, title ){
/* add new marker */
marker = new google.maps.Marker({
position:{ lat:lat,lng:lng },
title:title,
draggable:true,
map:map
});
/* store reference */
markers.push( marker );
}
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
draggable:true,
map: map // replaces marker.setMap(map);
});
/* for testing I only want it to run for a few times */
var i=0;
var m=10;
var igm=setInterval(
function() {
/* testing */
i++;
if( i > m ) clearInterval( igm );
/* testing */
$.ajax({
dataType:'JSON',
method: 'post',
url: document.location.href,
success: function(data) {
/* clear old markers */
markers.forEach( function( e,i,a ){
e.setMap( null );
console.log( 'remove marker:%o', e );
});
for( var o in data ){
var lat=Number(data[o].lat);
var lng=Number(data[o].lng);
var title=data[o].title;
/* Watch the console, see what you get here */
console.log( 'lat:%s, lng:%s',lat,lng );
addmarker.call( this, map, lat, lng, title );
}
},
error: function( err ){
console.warn( 'Error: %s',err );
}
})
}, 5000 );
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
example debug info from console:
remove marker:Object { __gm={...}, gm_accessors_={...}, position=(54.9094444444, -7.289444444440051), more...}
remove marker:Object { __gm={...}, gm_accessors_={...}, position=(56.306252, -3.2225129999999353), more...}
remove marker:Object { __gm={...}, gm_accessors_={...}, position=(54.9616666667, -6.9694444444400006), more...}
lat:56.6022222222, lng:-2.63416666667
lat:56.56138345735925, lng:-2.935781240463257
lat:54.5044444444, lng:-7.35222222222
I am working on a tracking system.
I get gps lat long values from database and then show marker on map,
and refresh a page after 30 seconds to check may b values updated on server.
my code is given below.
may map show page.
<!DOCTYPE html />
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"> </script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<title>GoogleMaps</title>
<script>
function initialize(lang,lat) {
var myLatlng = new google.maps.LatLng(lang,lat);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var contentString = 'Location NAme';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Location NAme'
});
}
function show_map(){
$.ajax({
type: "POST",
url: "some.php"
})
.done(function( msg ) {
alert(msg);
var obj = jQuery.parseJSON(msg);
initialize(obj.lang,obj.lat);
});
}
setInterval(show_map,30000);
</script>
</head>
<body onLoad="show_map()">
<div id="map_canvas" style="width: 100%; height: 100%;">
</body>
</html>
my PHP page is:
<?php
mysql_connect("localhost","root","")or die("error in connection");
mysql_select_db("gpsvalues");
$result = mysql_query("select * from gps");
$row = mysql_fetch_assoc($result);
$arr=array();
$arr = $row;
echo json_encode($arr);
?>
But it is not works fine.
For show multiple in a map you have to create array for lat long.
var locations;
locations=[
[lat1,long1],
[lat2,long2],
[lat3,long3],
[lat4,long4],
];
So your code should be change like
<script>
var locations;
locations=[
[lat1,long1],
[lat2,long2],
[lat3,long3],
[lat4,long4],
];
var map = new google.maps.Map(document.getElementById('maparea'), {
zoom: 14,
center: new google.maps.LatLng(6.778659644259302, 79.99540328979492),
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][0], locations[i][1]),
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>
You can call the add marker function through your php for every row in the gps..
<script>
<?php
mysql_connect("localhost","root","")or die("error in connection");
mysql_select_db("gpsvalues");
$result = mysql_query("select * from gps");
while($row = mysql_fetch_assoc($result))
{
echo "addmarker($row[lat], $row[lng]);"; //whatever way you have stored in your database
}
?>
function addmarker(lat, lng) {
var myLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Location NAme'
});
marker.setMap(map);
}
</script>
I have extracted the latitude and logitude from my database tables and have shown it on the google maps with markers.Now I want to get location to be displayed on the markers when they are clicked.I tried a lot but couldn't find the way.Can you please suggest how shall I proceeed?I am also giving the sample code which may help you.Kindly help me out.
<?php
$dbname='140dev';
$dbuser='root';
$dbpass='root';
$dbserver='localhost';
$dbcnx = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$sql = mysql_query("SELECT * FROM tweets1");
$res = mysql_fetch_array($sql);
$lat_d = $res['geo_lat'];
$long_d = $res['geo_long'];
// mimic a result array from MySQL
$result = array(array('geo_lat'=>$lat_d,'geo_long'=>$long_d));
?>
<!doctype html>
<html>
<head>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key="API_key"&sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
// Set static latitude, longitude value
var latlng = new google.maps.LatLng(<?php echo $lat_d; ?>, <?php echo $long_d; ?>);
// Set map options
var myOptions = {
zoom: 16,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Create map object with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
// uncomment the 2 lines below to get real data from the db
$result = mysql_query("SELECT * FROM tweets1");
while ($row = mysql_fetch_array($result))
echo "addMarker(new google.maps.LatLng(".$row['geo_lat'].", ".$row['geo_long']."),
map);";
?>
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
});
var contentString = latLng.lat() + " , " + latLng.lng();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
</script>
</head>
<body onload="initialize()">
<div style="float:left; position:relative; width:550px; border:0px #000 solid;">
<div id="map_canvas" style="width:950px;height:700px;border:solid black 1px;">
</div>
</div>
</body>
</html>
Improve your addMarker() function as it shows lat-lng values of clicked marker on infowindow:
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
});
var contentString = latLng.lat() + " - " + latLng.lng();
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
You can add location info as marker label. Just follow the example
http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.8/examples/basic.html
i have a problem with placing multiple marker in google map.here is my code.it display only one marker during page reloading and when page is complettly load then map is not display.
javascript code:
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
function initialize(lat,lon)
{
var myCenter=new google.maps.LatLng(lat,lon);
var mapProp = {
center:myCenter,
zoom:9,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
php code:
<?php
require_once 'geocode.php';
$addarray=array(0=>'a, ahmedabad,india',1=>'b,ahmedabad,india');
foreach($addarray as $add)
{
// define the address and set sensor to false
$opt = array (
'address' => urlencode($add),
'sensor' => 'false'
);
// now simply call the function
$result = getLatLng($opt);
// if status was successful, then print the lat/lon ?
if ($result['status']) {
echo '<pre>';
?>
<script>
initialize(<?php echo $result['lat'];?>,<?php echo $result['lon'];?>);
</script>
<?php
echo '</pre>';
}
}
?>
here first i got lat and lon according to address then i called javascript function to place marker.but something is missing or create a problem.
thanks in advance.
Thanks #Tudor Ravoiu for your help. it is solved by changing few things.
i have created array in json format in php and pass it to javascript.
<?php
require_once 'geocode.php';
$addarray=array(0=>'a,ahmedabad,india',1=>'b,ahmedabad,india',2=>'c,ahmedabad,india');
$lat1=array();
foreach($addarray as $add)
{
// define the address and set sensor to false
$opt = array (
'address' => urlencode($add),
'sensor' => 'false'
);
// now simply call the function
$result = getLatLng($opt);
// if status was successful, then print the lat/lon ?
if ($result['status'])
{
array_push($lat1,array($result['address'],$result['lat'],$result['lon']));
}
}echo json_encode($lat1);
?>
javascript code:
<script type="text/javascript">
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
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));
}
You have to set the array as a global var. Also notice that markers_array is an object that contain all the markers latitudes and longitudes and also other data if you want to initialize an infowindow also.
var markers;
var map;
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
for(i=0;i<markers_array.length;i++){
addMarker(markers_array[i].lat,markers_array[i].long);
}
function addMarker(lat,lng) {
var myLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
name: zip
});
markers.push(marker);
}
LATER EDIT:
Here is an example of the marker array in json format:
[
{
"name":"Marker 1 Italy",
"lat":"46.027482",
"long":"11.114502"
},
{
"name":"Marker 2 France",
"lat":"48.019324",
"long":"3.555908"
},
{
"name":"Marker 3 Spain",
"lat":"40.329796",
"long":"-4.595948"
}
]