Using php to create customized google map - php

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 ]

Related

How to pass data from MySQL to Google Maps

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?>;

Too much recurssion in google map

<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]);

google map multi marker

I have a project. I use google map and php in the project. When a query run I get latlong value from database. I defined limit 1 in the query. Later I show the position latlong value with a marker on the map. I want to show limit 5 with multi marker. How can I show all markers on the map? My query and query result on the below. The variable geom is a condition and my google map script some part on the below.
Query:
SELECT lat, lng from mytable where $geom limit 5;
Php code:
while ($row = pg_fetch_assoc($result)) {
$lat=$row['lat'];
$lng=$row['lng'];
}
Google Map js:
var myLatLng = {lat:<?php echo $lat;?>, lng:<?php echo $lng;?>};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 19,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
Only create the map once. Add all the markers to that map.
var map = new google.maps.Map(document.getElementById('map'));
var bounds = new google.maps.LatLngBounds();
while ($row = pg_fetch_assoc($result)) {
$lat = $row['lat'];
$lng = $row['lng'];
var myLatLng = {lat:<?php echo $lat;?>, lng:<?php echo $lng;?>};
bounds.extend(myLatLng);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
map.fitBounds(bounds); // center and zoom the map to show all the markers

Trying to make an array of latitude and longitudes dynamically in php

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.

What's the easiest way to display multiple locations using Google Map API with MySQL and PHP?

I would like to display over 100 locations each with detailed bubble contents (ie Company Name, Address, Phone Number, Website, Industry) on a custom Google Map. How can I fetch these locations from a MySQL database using Google Maps API 3 and PHP?
say you have an sql database of this type:
id/lat/lon/comment
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key= **your key** &sensor=true">
</script>
$sqlprep = "SELECT * FROM table_name";
$doselect = mysql_query($sqlprep);
echo "<script> var locations = [";
while ($loc = mysql_fetch_assoc($doselect)){
echo "['" .$loc[comment] ."', " . $loc['lat'] . ", " . $loc['lon'] . "";
}
echo " ];</script>";
and then in your java:
<script>jQuery(window).ready(function(){
function initialize() {
var myLatlng = new google.maps.LatLng( YOUR CENTER LAT,LAN HERE );
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
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
});
//adding the pop up windows here:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
initialize() ;
}); </script>
your html should be something like:
<html>
<body >
<div id="map_canvas" >
</div>
</body>
</html>
i might be missing some parentheses but you get the point ;)
hope it helps even 8 months later :)

Categories