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);
}
Related
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>
I'm not able to zoom to a particular area/location in Google maps which has multiple Map Pointers. At present it automatically centers the map covering all locations. But what I need is to zoom to a particular location upon opening the webpage. Here is my code,
<script>
jQuery(function ($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyA157quXbUlHHgm4wJJxzD49MivKgPSil8&sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
locations = <?php echo json_encode($sl_select_obj) ?>;
markerdata = JSON.parse('<?php echo json_encode($locations_data) ?>');
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap',
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers''
// $info='';
var markers = locations;
<?php
$total = count($locations_data);
$markerinfo = '';
$c = 0;
foreach ($locations_data as $key => $info):
if ($c != $total):
$markerinfo .="['<div class=\"info_content\"><h2>" . $info['loctitle'] . "</h2><h3>" . $info['site'] . "</h3><h3>View Full Office Details</h3></div>'],";
else:
$markerinfo .="['<div class=\"info_content\"><h2>" . $info['loctitle'] . "</h2><h3>" . $info['site'] . "</h3><h3>View Full Office Details</h3></div>']";
endif;
$c++;
endforeach;
?>
// Info Window Content
var infoWindowContent = [<?php echo $markerinfo; ?>]; //markerdata;
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i]["lat"], markers[i]["long"]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i]["address"],
icon: '<?php bloginfo('template_directory'); ?>/images/venue-direct-icon.png'
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
this.setZoom(7);
google.maps.event.removeListener(boundsListener);
});
map.fitBounds(markerBounds);
}
Try to add the "center" option like this:
var mapOptions = {
center: new google.maps.LatLng(51.5287718, -0.2416803),
mapTypeId: 'roadmap',
zoom: 15,
draggable: map_draggable,
scrollwheel: map_scrollwheel
};
EDIT: To help you this is a code similar that I use in my project: multiple positions, center on the first if only one, else I use google autocenter for all positions.
jQuery( document ).ready( function( $ ) {
if($(window).width()>991){
var map_draggable = true;
var map_scrollwheel = false;
} else {
var map_draggable = false;
var map_scrollwheel = false;
}
var offices = [];
$('#map-google-container')
.find('.hidden')
.each(function(){
offices[offices.length] =
{
"latitude":$(this).attr('latitude'),
"longitude":$(this).attr('longitude'),
"content":$(this).attr('content')
};
});
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(offices[0].latitude, offices[0].longitude),
draggable: map_draggable,
scrollwheel: map_scrollwheel,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: true
};
var map = new google.maps.Map(document.getElementById('map-google'), mapOptions);
var map_styles = [
{
featureType: "all",
stylers: [
{ hue: "#F69200" },
{ saturation: -50 }
]
},{
featureType: "water",
stylers: [
{ color: "#efefef" }
]
}
];
map.setOptions({styles: map_styles});
var image = '/include/images/marker.png';
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < offices.length; i++)
{
var content = offices[i].content;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(offices[i].latitude, offices[i].longitude),
map: map,
icon: image,
animation: google.maps.Animation.DROP,
title: content
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
if (offices.length > 1) { map.fitBounds(bounds); }
});
In my project I have to list all the offices and show a unique map with all of them. So in the HTML I put the information of all offices (hidden for the user). In JavaScript I loop through these properties and populate the map.
Hope it helps
Yes, I can able to find the solution, for those who are facing this similar issue may find it helpful,
var map_center_position = new google.maps.LatLng(34.0059657 ,-118.4440441);
bounds.extend(map_center_position);
map.fitBounds(bounds);
I am using the Google Maps API JS v.3 that has several hundred markers. I want to open a modal with info specific to the marker they clicked on. I'm plan on using PHP and AJAX to get the modal data from the MySQL Database, but I'm not sure how to determine which marker the user clicked...
Any help is greatly appreciated
`
var map;
//icon variables
/*
var dem = 'path/to/blue/icon.png';
var rep = 'path/to/red/icon.png';
var oth = 'path/to/grey/icon.png';
*/
var locations = [
<?php
$c = 0;
$nr = mysqli_num_rows($gethouses);
while($z = mysqli_fetch_array($gethouses)):
?>
['<?php echo $z['name_first'].' '.$z['name_last']; ?>', <?php echo $z['lat']; ?>, <?php echo $z['lng']; ?>, 4],
<?php
$c++;
endwhile;
?>
];
var map = new google.maps.Map(document.getElementById('google_world_map'), {
zoom: 10,
center: new google.maps.LatLng(39.675, -119.98),
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();
</script>`
You can add a custom parameter in your marker object (which value ideally should be unique).
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,
custom_param: some_unique_value
});
....
}
Then on your marker click event you can identify which marker is clicked by getting the value in this case marker.custom_param.
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
// make use of `marker.custom_param`
var myCustomParam = marker.custom_param;
}
})(marker, i));
}
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.
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"
}
]