I have a question. I make a project using google maps. i put 30 data on database. but when i wanna show the marker on the map, it only load for 10 data. also when I filter my data based on the category, it load for 10 data only. I check inspact element on my browser (im using mozilla) and found this error : "SyntaxError: unterminated string literal" what does it means?
Here's my code to show markers & map on the web :
<?php
$title = "Peta Masjid";
include_once "header.php";
?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-info panel-dashboard centered">
<div class="panel-heading">
<h2 class="panel-title"><strong> <?php echo $title ?> </strong></h2>
</div>
<div class="panel-body">
<div id="map" style="width:100%;height:380px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyAbXF62gVyhJOVkRiTHcVp_BkjPYDQfH5w">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-6.966667, 110.416664),
disableDefaultUI: true
};
var mapElement = document.getElementById('map');
var map = new google.maps.Map(mapElement, mapOptions);
setMarkers(map, officeLocations);
}
var officeLocations = [
<?php
$data = file_get_contents('http://localhost:8082/sig/getdata.php');
$no=1;
if(json_decode($data,true)){
$obj = json_decode($data);
foreach($obj->results as $item){
?>
['<?php echo $item->id_masjid ?>','<?php echo $item->nama_masjid ?>','<?php echo $item->alamat ?>', '<?php echo $item->longitude ?>', '<?php echo $item->latitude ?>','<?php echo $item->gambar ?>'],
<?php
}
}
?>
];
function setMarkers(map, locations)
{
var globalPin = 'img/tanda.png';
for (var i = 0; i < locations.length; i++) {
var office = locations[i];
var myLatLng = new google.maps.LatLng(office[4], office[3]);
var infowindow = new google.maps.InfoWindow({content: contentString});
var contentString =
'<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h5 id="firstHeading" class="firstHeading">'+ office[1] + '</h5>'+
'<div id="bodyContent">'+
'<p>' + office[2] + '</p>' +
'<p><img src="img/'+office[5]+'" style="width:50%;height:190px;" /></p>' +
'<p><a href=detail.php?id='+office[0]+'>Info Detail</p></a>'+
'</div>'+
'</div>';
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: office[1],
icon:'img/tanda.png'
});
google.maps.event.addListener(marker, 'click', getInfoCallback(map, contentString));
}
}
function getInfoCallback(map, content) {
var infowindow = new google.maps.InfoWindow({content: content});
return function() {
infowindow.setContent(content);
infowindow.open(map, this);
};
}
initialize();
</script>
</div>
</div></div></div>
</div>
</div>
<?php include_once "footer.php"; ?>
And here's code to get data from database (getdata.php)
<?php
include "connection.php";
$Q = mysql_query("SELECT * FROM mosques WHERE category = 'Mushola'")or die(mysql_error());
if($Q){
$posts = array();
if(mysql_num_rows($Q))
{
while($post = mysql_fetch_assoc($Q)){
$posts[] = $post;
}
}
$data = json_encode(array('results'=>$posts));
echo $data;
}
?>
You can use a counter in your while loop that counts to ten and then breaks the loop or an if statement than only runs if the counter is not 10
-Aron DC
Related
i have PHP code with MYSQL database and javascript where i ma using the java script in order to display the Google Map with markers where the code display markers based on their coordination.
i have some markers that have the same coordination but different ID so the map show just the last marker.
what i need is:
either to display all the markers that have the same coordination
or
display one marker with number that indicate the the total number of
the markers that have the same coordination.
code:
<script type="text/javascript">
var map,currentPopup;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: new google.maps.LatLng(33.888630, 35.495480),
mapTypeId: 'roadmap'
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
icon: iconBase + 'parking_lot_maps.png'
},
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
//icon: icons[feature.type].icon,
map: map
});
var markerCluster = new MarkerClusterer(map, marker,
{imagePath:
'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
var popup = new google.maps.InfoWindow({
content: '<b>Site ID :</b> ' + feature.info +'<br></br>'
+ '<b> Site Name :</b>' + feature.site_name +'<br></br>'
+ '<b>Coordinates :</b> '+ feature.position +'<br></br>'
+ '<b>height :</b> ' + feature.height,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
var features = [
<?php
$prependStr ="";
foreach( $wpdb->get_results("select c.siteID, c.latitude, c.longitude, c.height
, i.siteNAME
FROM site_coordinates2 c LEFT
JOIN site_info i
on c.siteID = i.siteID
where i.siteNAME = '".$site_name."'", OBJECT) as $key => $row) {
$latitude = $row->latitude;
$longitude = $row->longitude;
$siteid = $row->siteID;
$height = $row->height;
$siteName = $row->siteNAME;
echo $prependStr;
?>
{
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
info:'<?php echo $siteid;?>',
height: '<?php echo $height;?>',
site_name: '<?php echo $siteName;?>',
}
<?php
$prependStr =",";
}
?>
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
</script>
<?php
//echo "</table>";
}
?>
and i add this library to the code
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
I am initializing Gmap when the page is loading. Then I want to refresh map markers when ajax function is successfully completed. Can anyone help me? How can I do this?
I searched a lot on Google and SO but nothing helpful is found. so I asked a question. Before downvoting question please comment why you downvoted?
JS:
<script>
var map, infoBubble;
function initialize() {
var mapCenter = new google.maps.LatLng(52.5167, 13.3833);
$('#user_latitude').val(52.5167);
$('#user_longitude').val(13.3833);
var mapOptions = {
zoom: 3,
center: mapCenter,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
minZoom: 3,
scrollwheel: false
};
var infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var iw = new google.maps.InfoWindow();
var oms = new OverlappingMarkerSpiderfier(map, {
markersWontMove: true,
markersWontHide: true,
basicFormatEvents: true
});
var markers = [];
<?php foreach($pets as $pet):?>
var markerData = { lat: <?php echo $pet['pet_lat']?>, lng: <?php echo $pet['pet_long']?>, text: '<div class="shadow-box"><h3 class="title" style="font-size:20px;"><?php if($pet["pet_cat"] == 2):?><?php echo $pet["pet_name"];?><?php else:?><?php echo "Please Help me";?><?php endif;?></h3><p class="subtitle"><?php if($pet["pet_cat"] == 2):?><?php echo $pet["english"];?><?php else:?><?php echo $pet["dog_english"];?><?php endif;?></p><div class="image"><img src="<?php $img = unserialize($pet["img"]); echo base_url();?>uploads/<?php echo $pet["pet_hidenum"]."/".$img[0]?>" class="img-responsive" id="centerimg"></div><div class="quick-info clearfix"><div class="left"><p><span class="icon" style="font-size: 12px;"><img src="<?PHP echo base_url();?>assets/images/location.png" alt=""></span><?php echo $pet["reg_postal"].",".$pet["reg_city"].",".$pet["reg_country"]?></p><?php if($pet["showtel"] == "Yes"):?><p><span class="icon"><img src="<?PHP echo base_url();?>assets/images/phone.png" alt=""></span> <?php $mobile_phone_number = unserialize($pet["mobile_phone_number"]); echo $mobile_phone_number[0];?></p><?php endif;?><?php if($pet["pet_type"] == "Lost"):?><p id="rewardon"><span class="icon"><img src="<?PHP echo base_url();?>assets/images/reward.png" alt=""></span> Reward:€ (EUR) </p><?php endif;?></div><div class="right"><p style="margin-top: 14px;"><img src="images/mini_logo.png" style="width:95px;" alt=""></p><p>37070 Days Ago</p></div></div></div>' }
var marker = new google.maps.Marker({ position: markerData });
marker.setIcon({
<?php if($pet['pet_type'] == 'Found' && $pet['pet_cat'] == '1'):?>
url: "<?php echo base_url();?>assets/img/icons/greenpin.png"
<?php endif;?>
<?php if($pet['pet_type'] == 'Found' && $pet['pet_cat'] == '2'):?>
url: "<?php echo base_url();?>assets/img/icons/greenpin2.png"
<?php endif;?>
<?php if($pet['pet_type'] == 'Lost' && $pet['pet_cat'] == '1'):?>
url: "<?php echo base_url();?>assets/img/icons/redpin.png"
<?php endif;?>
<?php if($pet['pet_type'] == 'Lost' && $pet['pet_cat'] == '2'):?>
url: "<?php echo base_url();?>assets/img/icons/redpin2.png"
<?php endif;?>
})
marker.html = markerData.text;
google.maps.event.addListener(marker, 'spider_click', function(e) {
iw.setContent(this.html);
iw.open(map, this);
});
oms.addMarker(marker);
<?php endforeach;?>
window.map = map;
window.oms = oms;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
AJAX Function:
$.ajax({
method: 'POST',
url: formurl,
data: data,
success: function(response){
if(response != ''){
res = $.parseJSON(response);
var display = '<div class="listing-masonry" style="position: relative; height: 1815.52px;">';
$.each(res, function(i){
if(res[i].userid !== null){
if(res[i].pet_type === 'Lost'){
var ribbon = 'ribbon-lost';
}
else{
var ribbon = 'ribbon-found';
}
if(res[i].pet_type === 'Lost'){
var name = res[i].name;
}
else{
var name = 'Please help me';
}
if(res[i].pet_cat == 2){
var category = res[i].catbreed;
}
else{
var category = res[i].dogbreed;
}
display += ''; //display data refresh
//I want to refresh map at here. How can I do this?
}
});
display += '</div>';
}
else{
var display = '';
}
$("#js").html(display);
$("#php").hide();
}
})
Set your marker variable above. then inside the ajax success,
marker.setPosition({ lat : 'Your lat coord', long: 'your long coord' })
I have this script that call posts as markers into a Google Maps:
<?php
$args = array( 'post_type' => 'braiders', 'posts_per_page' => -1 );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ): ?>
<!-- WordPress has found matching posts -->
<div class="results-main-content">
<div class="results-group-items">
<?php $i = 1; ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if ( get_post_meta($post->ID, 'martygeocoderlatlng', true) !== '' ) : ?>
<div class="result-list-items">
<div class="results-left">
<?php
if ( has_post_thumbnail() ) {
// Get the post thumbnail URL
$feat_image = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
?>
<a href="<?php the_permalink(); ?>"><div class="result-items-image" style="background-image: url(<?php echo $feat_image; ?>);">
<p><?php the_title(); ?>
</p>
</div>
</a>
<?php } ?>
<!-- .result-items-image -->
</div>
<!-- results-left -->
<div class="result-right">
<?php the_content(); ?>
</div>
<!-- result-right -->
</div>
<!-- result-list-items -->
<?php endif; ?>
<?php $i++; ?>
<?php endwhile; ?>
</div>
<!-- results-group-items -->
</div>
<!-- .results-main-content -->
<script type="text/javascript">
var locations = [
<?php $i = 1; while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if ( get_post_meta($post->ID, 'martygeocoderlatlng', true) !== '' ) : ?> {
latlng: new google.maps.LatLng <?php echo get_post_meta($post->ID, 'martygeocoderlatlng', true); ?>,
info: document.getElementById( 'item<?php echo $i; ?>' )
},
<?php endif; ?>
<?php $i++; endwhile; ?>
];
</script>
and this next script that displays the map based on manually coded latlng:
var infowindow = new google.maps.InfoWindow();
var pinkmarker = new google.maps.MarkerImage('/wp- content/themes/halfempty/pink_Marker.png', new google.maps.Size(18, 32) );
var shadow = new google.maps.MarkerImage('/wp- content/themes/halfempty/shadow.png', new google.maps.Size(37, 34) );
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(35.1495343, -90.0489801),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: locations[i].latlng,
icon: pinkmarker,
shadow: shadow,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].info);
infowindow.open(map, marker);
}
})(marker, i));
}
}
I would like to know how to alter the above .js script that centers the Google to actually center the map based on user location when they access the page through their browser?
All I know is I need to dynamically pull the latlng of the visitor/user instead of manually coding it.
Thank you for taking a crack at it.
You can use the following script:
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
user_location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(user_location);
});
} else {
/* Browser doesn't support Geolocation */
}
Caveat: Some browsers do not support this without SSL. As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.
Your code should now look like this:
var infowindow = new google.maps.InfoWindow();
var pinkmarker = new google.maps.MarkerImage('/wp- content/themes/halfempty/pink_Marker.png', new google.maps.Size(18, 32) );
var shadow = new google.maps.MarkerImage('/wp- content/themes/halfempty/shadow.png', new google.maps.Size(37, 34) );
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(35.1495343, -90.0489801),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: locations[i].latlng,
icon: pinkmarker,
shadow: shadow,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].info);
infowindow.open(map, marker);
}
})(marker, i));
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
user_location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(user_location);
});
} else {
/* Browser doesn't support Geolocation */
}
}
I want to insert a google map in a div(html) which generates through a while loop. Google map gets coordinates from the database.
It should appear as in this image
Since I need to use a google map api key, I used following code.
But, It shows a map, only in the first div, using the last coordinates of the database, and doesn't show any other map in any other divs.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function currentUsers($connection){
$sql = "SELECT * FROM user ";
$result = mysqli_query($connection, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
$userID = $row['id'];
$firstName = $row['firstname'];
$country = $row['country'];
$latitude = $row['latitude'];
$longitude = $row['longitude'];
echo '<div>
<div align = "left">
<h3>'. $userID. " ". $firstName. " ". $country. '</h3>
</div>
<div id = "map" align = "right">
<script> <!--Google map api-->
function initMap() {
var x = '. $latitude. ';
var y = '. $longitude. ';
var myLatLng = {lat: x, lng: y};
var map = new google.maps.Map(document.getElementById(\'map\'), {
center: myLatLng,
scrollwheel: true,
zoom: 4
});
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
title: \'Hello World!\'
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</div>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
<html>
<head><title></title>
<style> #map {width: 500px; height: 400px; } </style> <!--Size of the map-->
</head>
<body></body>
</html>
ID of each div should be unique. Try this
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function currentUsers($connection){
$sql = "SELECT * FROM user ";
$result = mysqli_query($connection, $sql);
$x= 0;
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
$userID = $row['id'];
$firstName = $row['firstname'];
$country = $row['country'];
$latitude = $row['latitude'];
$longitude = $row['longitude'];
echo '<div>
<div align = "left">
<h3>'. $userID. " ". $firstName. " ". $country. '</h3>
</div>
<div id = "map_'.$x.'" align = "right">
<script> <!--Google map api-->
function initMap() {
var x = '. $latitude. ';
var y = '. $longitude. ';
var myLatLng = {lat: x, lng: y};
var map = new google.maps.Map(document.getElementById("map_'.$x.'"), {
center: myLatLng,
scrollwheel: true,
zoom: 4
});
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
title: \'Hello World!\'
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</div>
</div>';
$x++;
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
<html>
<head><title></title>
<style> #map {width: 500px; height: 400px; } </style> <!--Size of the map-->
</head>
<body></body>
</html>
You can only reliably include the API once. Currently you are including the API for each map you add.
You can also only have one function with the name initMap, currently you are including multiple versions of that function.
You can only have one div with id="map", currently you have one for each location.
related question (javascript only, no PHP): Adding multiple map canvases to window - Google Maps Javascript API v3
This is 100% working for me i've tested this code
<?php
$arr='';
$connection = mysqli_connect('localhost', 'root', '', 'users');
function currentUsers($connection){
$sql = "SELECT * FROM user";
$result = mysqli_query($connection, $sql);
$x= 0;
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
$userID = $row['id'];
$firstName = $row['firstname'];
$country = $row['country'];
$arr[] = array($row['latitude'],$row['longitude'],$x);
echo '<div style="width:100%;">
<div style="width:250px; height: 150px; float :left;">
<h3>'. $userID. ". ". $firstName. " ". $country. '</h3>
</div>
<div id = "map_'.$x.'" style="width:250px;height: 150px;"> </div>
</div>';
$x++;
}
echo '<script> var mymaps ='.json_encode($arr).'</script>';
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>
<script>
var maps = [];
function initialize(id, myLatLng) {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 9,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
maps[id] = new google.maps.Map(document.getElementById('map_'+id),
mapOptions);
var marker = new google.maps.Marker({
map: maps[id],
position: myLatLng,
title: 'Hello World!'
});
}
$(document).ready(function(){
for( var i = 0; i < mymaps.length; i++)
{
var x = parseFloat(mymaps[i][0]);
var y = parseFloat(mymaps[i][1]);
var myLatLng = {lat: x, lng: y};
google.maps.event.addDomListener(window, 'load', initialize(mymaps[i][2],myLatLng)); // two calls
}
});
</script>
I get the Coordinates and the Names and "ID" out of an MySQL Table but why is in every Marker the same Text an also the same link ?
Why is the text not different ???
It show only the last ID but it should add after every element in the data base an other marker !
The markers are at the right Position and the "Content" is in the Source Code also right but not at the markes why ?!
Please Help
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(51.124213, 10.60936),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new
google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var contentString;
var elementeInArray = 0;
var LatLngList = new Array;
<? php
$i = 1;
foreach($FertigID as $ID) {
$result = mysql_query("SELECT * FROM Daten_CH WHERE Objektnummer = ".$ID.
"");
while ($Ergebnisse = mysql_fetch_array($result)) {
// Werden alle ergebnisse (ID´s) in einen Array geschriebenn
echo $$Ergebnisse["Objektnummer"];
if (isset($Ergebnisse["Gis_y"]) && $Ergebnisse["Gis_y"] != "" &&
$Ergebnisse["Gis_y"] != " ") {
echo $i; ?>
// MARKER TEXT
contentString = '<?php echo $i; ?> </br><?php echo
$Ergebnisse["Objektname"]; ?>
</br><a href="Change.php?ID=<?php echo $ID; ?>">
<input type="button" value="BEARBEITEN"></button></a>';
var Position = new google.maps.LatLng( <? php echo $Ergebnisse["Gis_y"]; ?> , <? php echo $Ergebnisse["Gis_x"]; ?> );
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker <? php echo $i; ?> = new google.maps.Marker({
position: Position,
map: map,
title: '<?php echo $Ergebnisse["AA_Objektname"]; ?>'
});
google.maps.event.addListener(marker <? php echo $i; ?> , 'click', function () {
infowindow.open(map, marker <? php echo $i; ?> );
});
LatLngList[elementeInArray] = new google.maps.LatLng( <? php echo $Ergebnisse["Gis_y"]; ?> , <? php echo $Ergebnisse["Gis_x"]; ?> );
elementeInArray++;
<? php
}
}
$i++;
}
?>
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend(LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds(bounds);
var opt = {
minZoom: 1,
maxZoom: 12
};
map.setOptions(opt);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Because you should assign the contentString to the marker, and update the infowindow with each markers assigned content instead. As it is now, the only contentString available is the last created. Furthermore, you really dont have to create multiple numbered markers. You just need one marker reference only.
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: Position,
map: map,
content: contenString, // <-- assign content to the marker itself
title: '<?php echo $Ergebnisse["AA_Objektname"]; ?>'
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.content);
infowindow.open(map, this);
});
This would do the trick.