multiple marker on googlemaps from php and mysql - javascript

i try to make multiple markers on googlemaps and taking data from database.
this is my code
<script>
<?php
$query = $db->query('SELECT * FROM tbl_kabkot WHERE 1=1 AND latitude !=0 AND longitude !=0');
while($row = $query->fetch()){
$nama_kabkot = $row[nama_kabkot];
$longitude = $row[longitude];
$latitude = $row[latitude];
?>
var markers = [
[<?= $nama_kabkotv ?>, <?= $latitude ?>, <?= $longitude ?>]
];
<?php } ?>
function initMap() {
var latlng = new google.maps.LatLng(-33.92, 151.25);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("peta"),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
But this code only shows one value from the database.
how can i show a multiple markers with database?

The initial sql query has a redundant where clause due to 1=1 but I assume that is for testing. The markers variable in the original code is being over-written on each iteration through the loop so the array will only have one item.
<?php
/* lat/lng data will be added to this array */
$locations=array();
$query = $db->query('SELECT * FROM tbl_kabkot WHERE 1=1 AND latitude !=0 AND longitude !=0');
while( $row = $query->fetch() ){
$nama_kabkot = $row['nama_kabkot'];
$longitude = $row['longitude'];
$latitude = $row['latitude'];
/* Each row is added as a new array */
$locations[]=array( 'name'=>$nama_kabkot, 'lat'=>$latitudem, 'lng'=>$longitude );
}
/* Convert data to json */
$markers = json_encode( $locations );
?>
<script type='text/javascript'>
<?php
echo "var markers=$markers;\n";
?>
function initMap() {
var latlng = new google.maps.LatLng(-33.92, 151.25);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("peta"),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>
// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initMap() {
var markerscenter = [
['Bondi Beach', -33.890542, 151.274856,],
['Bondi Beach2', -33.90542, 151.2748,]
];
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: {lat:Number(markerscenter[0][0]), lng:Number(markerscenter[0][1])}
});
setMarkers(map);
}
// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
var markers = [
['Bondi Beach', -33.890542, 151.274856,],
['Bondi Beach2', -33.90542, 151.2748,]
];
// Info Window Content
var infoWindowContent = [
'desc1','desc2'
];
function setMarkers(map) {
var image = 'markeimage.png';
var infoWindow = new google.maps.InfoWindow(), marker, i;
for (var i = 0; i < markers.length; i++) {
//var beach = beaches[i];
var marker = new google.maps.Marker({
position: {lat:Number(markers[i][0]), lng: Number(markers[i][1])},
map: map,
icon: image,
});
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
}
}
</script>

Related

Multiple markers are not properly showing in google map php

In my laravel project am trying to show locations of my clinics in google maps (Taking lattitude and longitude values from php database). Follwoing is my code in controller.
public function showClinicLocations($id)
{
$clinic = Clinic::find($id);
$locations = Location::where('clinicID', $id)->get();
return view('clinic.locations')->with(['locations' => $locations ,'clinic'=>$clinic]);
}
In view page am properly getting locations .When i consoled the locations.length am getting the result as 12 , its correct and also am getting complete locations name.
But when i tried to show it in marker only 11 locations are showing in google map marker. Following is the code in google map marker.
<script>
// var services =<?php echo json_encode($services);?>;
// console.log(services);
function initMap() {
var locations = <?php echo $locations ?>;
console.log(locations.length);
var j;
for (j = 0; j < locations.length; j++) {
var map = new google.maps.Map(document.getElementById('map'),
{zoom: 8,
center: {
lat: parseFloat(locations[j]['locationLat']),
lng:parseFloat(locations[j]['locationLong'])
}
}
);
setMarkers(map);
}
}
function setMarkers(map) {
var locations = <?php echo $locations ?>;
//var services = <?php echo $services ?>;
//console.log(services);
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
map: map,
position: {lat: parseFloat(locations[i]['locationLat']), lng:parseFloat(locations[i]['locationLong'])},
map: map,
title: locations[i]['locationName']
});
var infowindow = new google.maps.InfoWindow()
var content = locations[i]['locationName'];
google.maps.event.addListener(marker,'click',
(function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker, content,infowindow));
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
What is the problem with the code of google maps to show markers
You wanna generate the map only once and maybe also fit the map to the bounds of all displayed markers:
var locations = JSON.parse("<?php echo $locations ?>");
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: {
lat: parseFloat(locations[0]["locationLat"]),
lng: parseFloat(locations[0]["locationLong"])
}
});
setMarkers(map);
}
function setMarkers(_map) {
var boundsToFit = new google.maps.LatLngBounds();
for (var i = 0; i <= locations.length; i++) {
var marker = new google.maps.Marker({
map: _map,
position: {
lat: parseFloat(locations[i]["locationLat"]),
lng: parseFloat(locations[i]["locationLong"])
},
map: _map,
title: locations[i]["locationName"]
});
var infowindow = new google.maps.InfoWindow();
var content = locations[i]["locationName"];
google.maps.event.addListener(
marker,
"click",
(function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(_map, marker);
};
})(marker, content, infowindow)
);
boundsToFit.extend(marker.getPosition());
}
_map.fitBounds(boundsToFit);
}

Pass PHP Array to Google Maps Markers (Javascript)

I'm storing my data to a php array and trying to pass it to javascript to get google maps display all the points in the php array. bellow is the php code (simplified and the javascript code for google maps.
-----PHP CODE--------
foreach(json_decode($response)->data as $item){
$name= $item->user->name;
$latitude = $item->latitude;
$longitude = $item->longitude;
$Array[$count] = array('name'=>$name,'lat'=>$latitude, 'long'=>$longitude, 'rgb'=>$count);
$js_array = json_encode($Array);
$count++;}
-----javascript
<script type="text/javascript">
var locations = <?php echo $js_array;?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
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));
}
UPDATED JAVASCRIPT
var locations = <?php echo json_encode($js_array);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(<?php echo $latitude;?>, <?php echo $longitude;?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
console.log(locations[i].lat);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].long),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].name);
infowindow.open(map, marker);
}
})(marker, i));
}
In your updated javascript, you need to remove json_encode (already present in PHP). You were doing it twice.

Place multiple php vars as lat/long in Google Maps

This is what I have... PHP pulls down 10 pairs of lat/long from an API url which I have managed to get working okay but I cannot seem to plot them on a map with multiple markers labelled 1-10.
My php code:
<?php
// Loading Domus API
$url_search = 'http://url/site/go/api/search';
$xml_search = #simplexml_load_file($url_search) or die ("no file loaded") ;
//Displaying latitude and longutude
$house = json_encode($house);
}; ?>
JavaScript bit:
var locations = "<?php foreach($xml_search->property as $house) { echo $lat = $house->address->latitude , $long = $house->address->longitude;}; ?>";
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(37.0625,-95.677068),
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));
}
Which is then needs to be displayed in here
<div id="map" style="width: 500px; height: 400px"></div>
But I just get a blank page, of course.
Okay, I've managed to figure it out.
Here is my php code in the head part
<?php
// Loading Domus API
$url_search = 'http://url/site/go/api/search';
$xml_search = #simplexml_load_file($url_search) or die ("no file loaded") ;?>
Then I have my javascript
// Load property ID followed by Lat and Long for each house (total of 10)
var locations = [<?php foreach($xml_search->property as $house) {
echo '['.$house->id. ',' .$house->address->latitude. ',' .$house->address->longitude.'],';
} ?>];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = new Array();
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
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
function AutoCenter() {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
$.each(markers, function (index, marker) {
bounds.extend(marker.position);
});
// Fit these bounds to the map
map.fitBounds(bounds);
}
AutoCenter();
Works beautifully, now just need to set up labelled markers and I am good to go.

multiple marker in google map

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"
}
]

json returned array of markers are pointing to last markers

what i am doing is that i am placing multiple markers on map returned from json array,here is my code.my markers are plotted correctly but when i click on each marker it make info window of one marker that is last marker of array
function latLongCallback(latitutde,longitutde){
var latlng = new google.maps.LatLng(latitutde, longitutde);
var options = {zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById('map'), options);
$.ajax({type: "GET",
dataType: 'json',
url: "http://www.xyz.com/xcv/xainee/test/markers.php",
success: function(response){
var total=response.length;
data_array,name,type,address,lat,lon,point,infowindow,marker,arrival,departure,notes;
var icon_image = 'http://www.xyz.com/userftp/fawad/test/images/map-icon.png';
for(var i=0; i < total; i++)
{
data_array=response[i];
name=data_array['name'];
address=data_array['address'];
arrival=data_array['arrival'];
departure=data_array['departure'];
notes=data_array['notes'];
lat=data_array['lat'];
lon=data_array['lon'];
contentString ="Name : "+name+"<br/> Location : "+address+"<br/> Arrival :"+arrival+"<br/> Departure : "+departure+"<br/> Notes : "+notes;
point = new google.maps.LatLng(lat,lon);
infowindow = new google.maps.InfoWindow({content: contentString,maxWidth: 400,maxHeight: 201});
marker = new google.maps.Marker({map: map,icon: icon_image, position: point});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker);});
}
}
});
return;
}
here is my markers.php
<?php session_start();
include_once("database.php");
$data=array();
$retrive_marker_query = "SELECT fb_user.name,schedule.location,schedule.arrival,schedule.departure,schedule.notes,schedule.lat,schedule.lon FROM schedule,fb_user where fb_user.fb_id = schedule.fb_id";
$result = db_execute($retrive_marker_query);
$cnt=0;
while ($row = #mysql_fetch_assoc($result)){
$name=$row['name'];
$address= $row['location'];
$arrival= $row['arrival'] ;
$departure= $row['departure'] ;
$notes= $row['notes'] ;
$lat= $row['lat'];
$lon= $row['lon'];
$data[$cnt]['name']=$name;
$data[$cnt]['address']=$address;
$data[$cnt]['arrival']=$arrival;
$data[$cnt]['departure']=$departure;
$data[$cnt]['notes']=$notes;
$data[$cnt]['lat']=$lat;
$data[$cnt]['lon']=$lon;
$cnt++;
}
$data=json_encode($data);
echo($data);
?>
why my markers content are same although all markers are plotted in different lat and lon

Categories

Resources