I'm confused about how to pass data from PHP to my google maps API.
<script>
<?
$dbFirst = new database;
$dbFirst->query("SELECT getLatitude,getLongitude FROM t_report
WHERE phoneNumber='$idimei' AND tanggal BETWEEN '$tgl1 00:00:00' and '$tgl1 23:59:59' AND (km IS NOT NULL AND km !='') ORDER BY ID ASC LIMIT 1");
$rowFirst=$dbFirst->tampilkan();
while ($rowFirst=$dbFirst->tampilkan()){
$lat=$rowFirst['getLatitude'];
$lon=$rowFirst['getLongtitude'];
}
?>
var marker;
function initMap() {
var mark1 = {lat:X, lng:Y};
var map = new google.maps.Map(document.getElementById('map'), {
center: mark1,
zoom: 18
});
marker = new google.maps.Marker({
position: mark1,
animation: google.maps.Animation.DROP,
map: map
});
marker.addListener('click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
</script>
how do I put $lat and $lon to my mark1 X and Y variable? I'm confused on how to pass data outside PHP.
Thanks for answering
You can use the following method to pass data from PHP variable to JS
Suppose this is where you are querying data from DB and storing it in a variables $lat and $lon
<?php
//data from DB
$lat = "xx.xx";
$lon = "xx.xx";
?>
<script>
// then echo it into the js
// and assign to a js variable
let lat = '<?php echo $lat ;?>';
let lon = '<?php echo $lon ;?>';
// then
function initMap() {
var mark1 = {lat:lat, lng:lon};
var map = new google.maps.Map(document.getElementById('map'), {
center: mark1,
zoom: 18
});
marker = new google.maps.Marker({
position: mark1,
animation: google.maps.Animation.DROP,
map: map
});
marker.addListener('click', toggleBounce);
}
</script>```
To pass variable $lat and $lon from PHP to X and Y in javascript you can do like this:
var marker;
var X ="<?php echo $lat; ?>";
var Y ="<?php echo $lon; ?>";
or more shorter:
var marker;
var X =<?$lat?>;
var Y =<?$lon?>;
Related
<script type='text/javascript'>
jQuery(document).ready(function($){
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
var encodedString;
var stringArray = [];
encodedString = document.getElementById("encodedString").value;
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
$encodedString = "";
$x = 0;
$result = mysql_query("SELECT * FROM `table-name`");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
if ( $x == 0 )
{
$separator = "";
}
else
{
$separator = "****";
}
$encodedString = $encodedString.$separator.
"<p class='content'><b>Lat:</b> ".$row[1].
"<br><b>Long:</b> ".$row[2].
"<br><b>Name: </b>".$row[3].
"<br><b>Address: </b>".$row[4].
"</p>&&&".$row[1]."&&&".$row[2];
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
</div>
<div id="map_canvas"></div>
I have used above code for google map location from MySQL database.
Above code fetch lat, Lang from MySQL database and dynamically create google map.
When I run above code It gave me error like that:
There are two errors named too much recursion & initMap is not function.
Can anybody help me to sort out it.
Thanks in advance.
You have not defined initMap in your js file. That's why you are getting that error. You probably need to remove the callback part from the google map api script
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
To
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" async defer></script>
Also check if the lat and lon contain valid numeric values in the following statement
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
I am having error of OVER_QUERY_LIMIT in using google maps api v3. I want to add markers from database by geocoding. If I use limit in sql query then the markers are shown, if I increase the limit greater than 10 then its showing the error.
<?php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('dbname') or die(mysql_error());
$result = mysql_query("SELECT * FROM deal WHERE cityID=44 LIMIT 10") or die(mysql_error());
$count = 0;
echo mysql_num_rows($result);
$row = mysql_fetch_array($result);
?>
<script type="text/javascript">
var geocoder;
var map;
//var address;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = "<?php echo $row['address']; ?>";
//address = '3655 South Durango, Las Vegas, NV 89147';
//alert(address);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
while($row = mysql_fetch_array($result)){
?>
geocoder.geocode( { 'address': "<?php echo $row['address']; ?>"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
"<h1 id='firstHeading' class='firstHeading'><?php echo $row['businessName']; ?></h1>"+
'<div id="bodyContent">'+
"<p><?php echo $row['longDesc']; ?></p>"+
'<p>Attribution: Uluru, <a href="#">'+
'Click To See</a> '+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
<?php sleep(1); ?>
} else {
alert("Geocode was not successful for the following reason: " + status);
//setTimeout("wait = true", 2000);
}
});
<?php } ?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You can't geocode more than 2500 locations per day with free version.
Based on my memories, you also have to wait approximatively 0.5 seconds between two geocods, so you must delay you script ; else you'll be blocked.
I am trying to make an array of latitudes and longitudes using cities that I have in a mySQL database. This is what I have so far. I am trying to set up the array variable in javascript, and echo out the fields inside. The "markers" array is read to make markers appear on the google map at the desired locations:
EDIT: Here is the entire script
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
var markers = [
<?php
//orgnize fans by city
$query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
//pulls the city, state code from the database and stores it as a string in $address
$address = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
$googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';
$json = file_get_contents(sprintf($googleApi, $address));
$resultObject = json_decode($json);
$location = $resultObject->results[0]->geometry->location;
$lat = $location->lat;
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
}
?>
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Current City'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
When I open the html, I call initialize and make the canvas:
<body onload="initialize()">
<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>
You have a typo: sometimes you use long, at other times lng.
in the code segment:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});}
while earlier you use
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$long.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
In effect, your echo statement, which should be producing longitudes in your array, is referencing a non-initialized variable, $long. Fix that and you should be good to go. In other words, change
$lng = $location->lng;
to
$long = $location->lng;
(or change your echo statement...)
My earlier answer dealt with the typo. I think there's a fundamental issue with "how to draw maps with the google API". The following code snippet (from google JavaScript API shows an example of using overlays (which is what a marker is):
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP, }
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!" });
// To add the marker to the map, call setMap();
marker.setMap(map);
Several of these steps appear to be missing from your code - maybe you didn't show them, or maybe you didn't realize you needed them?
EDIT: even after you posted your full code, I still don't see certain things I would expect.
Here are one thing you can try for sure: call the google API before referencing it: add this line
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"> </script>
right below <head>, before your <script>
Fixing just this, and taking out a bunch of "superfluous" (for the purpose of "getting a map with a pin") lines, allowed me to create a simple file that can render a map of New York, NY with one marker on it. The source code can be found at http://www.floris.us/SO/maptest.php.txt . From there, you can add more stuff back in...
Further edit: with the lessons learnt, I made http://www.floris.us/SO/maptestFull.php which has most of the functionality you were looking for (not the DB lookup, which I don't have, obviously). Once again, source code is copied in .php.txt file so you can look at it. Slightly messy (from trying to turn things on/off) - you will have to look closely to see all the changes I made.
I am trying to create a custom google map using Longitudes and Latitudes that I have in my sql database. So I am trying to place these results directly into my jquery code for the geocoder. But it is not working. Does anyone have ANY idea how I could do this?? I have looked up everything possible and can not find an answer. Thank you so much in advance. Here is my code:
<script type='text/javascript'>//<![CDATA[
var map;
var global_markers = [];
[<?php
include 'admin/dbconn.php';
$getLoc = mysql_query("SELECT * FROM EanHotels WHERE City = 'Acapulco'") or die(mysql_error());
while($row = mysql_fetch_array($getLoc)){
$name = $row['name'];
$lat = $row['Latitud'];
$lon = $row['Longitude'];
$address = $row['Address1'];
echo $lat;
echo $lon;
?>
var markers = [[<?php echo $lat ?>, <?php echo $lon ?>, '<?php echo $name ?>'], <?php } ?>
];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker();
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
//]]>
</script>
Have you checked the output of this script on the markers variable? This seems to have something with the formatted number output.
JavaScript expects numbers in the international format, with periods as the decimal separator: 10.2
In some places the server is configured to use comma as the decimal separators, so the output of your script would return an array of numbers, not a number with decimal places:
[[ 1,00012, 1,45678, 'name' ]]
Also, you have an extra comma at the end of the markers variable declaration, before the closing square bracket ]
I have a json output that shows my info correctly but i am having a hell of a time getting it to show a icon on each pair of lat+lng from my DB
Here is my current code
<?php
require('inc/db.inc.php');
mysql_connect($connect, $user, $pword) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$sql=mysql_query("SELECT store_lat,store_long FROM location WHERE status='Active'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
$locations=(json_encode($output));
?>
<script src="http://maps.google.com/maps/api/js?sensor=false&key=MY_API_KEY" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var image = 'images/icon.png';
var myLatlng = new google.maps.LatLng(42.548625, -92.548765);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var poiJson = <? echo $locations ?>;
for (var i = 0;i < poiJson.length; i += 1) {
var lat = poiJson[i].store_lat;
var lng = poiJson[i].store_long;
addMarker(lat,lng,i);
};
}
function addMarker(lat,lng,no){
var latlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
map: map
// if i uncomment the icon line no map will show at all
//icon: image
});
}
</script>
<? include "header.php"; ?>
<p>
<table width="1024">
<tr>
<td align="center" valign="top"><div id="map_canvas" style="width: 95%; height: 600px;"></div></td>
</tr>
</table>
</p>
</body>
</html>
Edit
if i change the image into the addMarker function this dose not change anything.
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(42.548625, -92.548765);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var poiJson = <? echo $locations ?>;
for (var i = 0;i < poiJson.length; i += 1) {
var lat = poiJson[i].store_lat;
var lng = poiJson[i].store_long;
addMarker(lat,lng,i);
};
}
function addMarker(lat,lng,no){
var image = 'images/icon.png';
var latlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
map: map
//icon: image
});
}
</script>
There is no image defined in the scope of addMarker (hence you will get an error). It is only local to initialize. Either define it in addMarker or make it global.