using mysql and php with google maps - javascript

I'm trying loop through every row in a table and set a marker using the value provided in the "address column". The js code and the php code until setMarker() works fine but I'm not sure how to go about using the function inside php code.
<?php
require 'private/database.php';
$sql = "SELECT * FROM form;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<script>setMarker($row["address"]);</script>';
}
} else {
echo '<script>console.log("ERROR: marker database empty");</script>';
}
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: {lat: 24.149950, lng: 120.638610},
mapId: '63d22d3ae6cf15ff'
});
}
// geocoder
function setMarker(address) {
const geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address, componentRestrictions: {
country: 'TW'}}, (results, status) => {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert(`Geocode unsuccessful for address: "${address}"\nSTATUS CODE: ${status}`);
}
});
}

This is more or less what I meant with the comment I made - this way the map is created by the initMap callback function before any attempts to create the markers is made - which might not be the case in the original. This is quickly put together and not tested.
<script>
var map;
<?php
require 'private/database.php';
$sql = "SELECT * FROM form;";
$result = mysqli_query($conn, $sql);
$data=array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row;
}
// create the js variable
printf(
'var json=%s;',
json_encode( $data )
);
?>
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: {lat: 24.149950, lng: 120.638610},
mapId: '63d22d3ae6cf15ff'
});
Object.keys(json).forEach( key => {
let obj=json[ key ];
setMarker( obj['address'] )
})
}
function setMarker(address) {
const geocoder = new google.maps.Geocoder();
geocoder.geocode( { address: address, componentRestrictions: { country: 'TW'} }, (results, status) => {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert(`Geocode unsuccessful for address: "${address}"\nSTATUS CODE: ${status}`);
}
});
}
</script>

Related

Trying to get markers dynamically from database using php and javascript

I am trying to get markers dynamically from the database using sql and php. The problem that i am facing is making the marker array in javascript. I have already referred the questions asked on stackoverflow but no luck...
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
initMap(latitude,longitude);
addMarker(latitude,longitude);
}
function initMap(latitude,longitude){
var options = {center :{lat:latitude, lng :longitude} ,
zoom:8
}
var map = new google.maps.Map(document.getElementById('map'),options);
var marker = new google.maps.Marker({
position:{lat:latitude, lng :longitude},
map:map
})
}
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{';
echo $lat;
echo ',';
echo $long;
echo '},';
}
?>
];
function addMarker(props){
alert(markers.length)
}
$(document).ready(function(){
getLocation();
});
javascript from source
{19.1643153,72.98971789999996},{19.1816553,72.9711542},{19.2403305,73.13053949999994},{29.6856929,76.99048249999998},{19.2532887,73.13668610000002},{19.2532887,73.13668610000002},{19.2292364,72.85967119999998},{19.2292364,72.85967119999998},{19.0606917,72.83624970000005},{18.5596581,73.7799374},{19.157935,72.99347620000003},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{19.2403305,73.13053949999994},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{53.9332706,-116.5765035},{19.157935,72.99347620000003},{19.2183307,72.97808970000006},{19.157935,72.99347620000003},{53.9332706,-116.5765035},{46.227638,2.213749000000007},{19.157935,72.99347620000003},{19.157935,72.99347620000003},
The array of marker positions is not a valid javascript array. Make the positions to be google.maps.LatLngLiteral objects. Change the code that generates the javascript for your markers array from:
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{';
echo $lat;
echo ',';
echo $long;
echo '},';
}
?>
];
To:
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{lat:';
echo $lat;
echo ', lng:';
echo $long;
echo '},';
}
?>
];
So your markers array looks like this:
var markers = [
{lat: 19.1643153, lng: 72.98971789999996},
{lat: 19.1816553, lng: 72.9711542},
{lat: 19.2403305, lng: 73.13053949999994},
// ...
];
proof of concept fiddle
code snippet:
var bounds;
var map = null;
function initMap(latitude, longitude) {
var options = {
center: {
lat: latitude,
lng: longitude
},
zoom: 8
}
map = new google.maps.Map(document.getElementById('map'), options);
var marker = new google.maps.Marker({
position: {
lat: latitude,
lng: longitude
},
map: map
})
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
addMarker(markers[i]);
}
map.fitBounds(bounds);
}
var markers = [{lat:19.1643153, lng:72.98971789999996}, {lat:19.1816553, lng:72.9711542}, {lat:19.2403305, lng:73.13053949999994}, {lat:29.6856929, lng:76.99048249999998}, {lat:19.2532887, lng:73.13668610000002}, {lat:19.2532887, lng:73.13668610000002}, {lat:19.2292364, lng:72.85967119999998}, {lat:19.2292364, lng:72.85967119999998}, {lat:19.0606917, lng:72.83624970000005}, {lat:18.5596581, lng:73.7799374}, {lat:19.157935, lng:72.99347620000003}, {lat:30.900965, lng:75.85727580000002}, {lat:19.2403305, lng:73.13053949999994}, {lat:19.157935, lng:72.99347620000003}, {lat:53.9332706, lng:-116.5765035}, {lat:19.157935, lng:72.99347620000003}, {lat:19.2183307, lng:72.97808970000006}, {lat:46.227638, lng:2.213749000000007}];
function addMarker(props) {
console.log(JSON.stringify(props));
var marker = new google.maps.Marker({
position: props,
map: map
});
console.log(marker.getPosition().toUrlValue(6));
bounds.extend(marker.getPosition());
}
google.maps.event.addDomListener(window, "load", function() {
initMap(19.16, 75.857)
});
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Javascript & PHP show multiple trackers in Google Maps API

Currently, I'm developing a system that will bring all latitude and longitude from MySQLi DB, and will output every data on the page. Here is my PHP code (working without any problem):
header('Content-Type: text/html; charset=utf-8');
require('database.php');
$query = mysqli_query($mysqli, "SELECT * FROM `tracking`");
if (!$query)
{
die('Error: ' . mysqli_error($mysqli));
}
if(mysqli_num_rows($query) > 0){
$getList = array();
while ($row = mysqli_fetch_assoc($query)) {
$getList[] = $row;
}
for($i = 0, $l = count($getList); $i < $l; ++$i) {
echo $getList[$i]['lat'].",".$getList[$i]['lon']."\n";
}
}
e.g output: -71.99991299555996,-83.18116602 -22.809918399999997,-43.4211132 -22.8540416,-43.2488448
Now, I need bring all data and put into an array, and put whole latitude/longitude to markers in Google Maps. Check what I have tried:
var check = false;
function refreshAll() { // This function will be called every 60 seconds
var locations = [];
locations.length = 0;
$.ajax({
type: "GET",
url: "show.php",
success: function(x)
{
var items = x.split("\n");
for(i=0; i<items.length; i++){
var data = items[i];
if ((items[i]).length > 1) {
locations.push(items[i].trim());
}
}
if (check == false) { // this will avoid map refreshing, I need only markers update.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
check = true;
}
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
alert(locations[i]);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
}
}
});}
The problem is: the markers is not being set, and have no errors in console. I'm working on this in the last two days and can't find any solution. Can you help me? Thank you.
As you can see here in the docs, the LatLng object is different than the one you are using.
So, replace:
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
With
locations[i] = locations[i].trim().split(',');
var latLng = {lat: Number(locations[i][0]), lng: Number(locations[i][1])};
marker = new google.maps.Marker({
position: latLng,
map: map
});
Check out, the map object is in your infoWindow variable, try to set there the positions.
This should be used inside the locations loop.
var pos = {
lat: latitude,
lng: longitude
};
infoWindow.setPosition(pos);

google maps show multiple location (Error: locations[i] is undefined)

I am trying to show multiple users location using Google Map API, I have to show all value from master_service_provider table for this I am using while loop.
But I am getting JavaScript error Type Error: locations[i] is undefined.
<div id="map"></div>
<script>
var map;
function initMap() {
var i = '0';
<?php
$result=$conn->query("SELECT * FROM `master_service_provider`");
$a=0;
while($row = mysqli_fetch_array($result)) {
$service_provider_id = $row['id'];
$fullname = $row['fullname'];
$fulladdress = $row['fulladdress'];
$phone = $row['phone'];
$lat = $row['lat'];
$lng = $row['lng'];
?>
var <?php echo 's'.$phone; ?> = {
info: '<h3><?php echo $fullname; ?></h3>\
<h4><?php echo $fulladdress; ?></h4>\
View Info',
lat: <?php echo $lat; ?>,
long: <?php echo $lng; ?>
};
var locations = [
[<?php echo 's'.$phone; ?>.info, <?php echo 's'.$phone; ?>.lat, <?php echo 's'.$phone; ?>.long, <?php echo $a++; ?>],
];
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));
i++;
<?php } ?>
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(19.198313, 72.893533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({});
var marker;
}
</script>
It should be something like this, I think.
Fill the ... parts yourself, but keep the general structure of the code.
Let me know if you get it to work
<?php
...
// do this on top, not in the middle of javascript
$result = $conn->query("SELECT id, lat, lng, fullname, fulladdress, phone FROM master_service_provider"); // don't use *, specify the columns you want
$mydata = array();
while($row = mysqli_fetch_assoc($result)) { // use _assoc rather than _array
$mydata[] = $row ; // push current row to the data object
}
// now we translate this php array to a javascript array of objects.
// it should resemble something like:
// var locations = [ {"id": "1", "lat":"4.51", "lng":"50.53", "fullname":"John Smith", ... }, {"id": "2", lat":"5.14", ...} ] ;
// use json_encode() to realize this
echo '<script>var locations = '. json_encode($mydata) .' ;</script>';
?>
<script>
var map;
function initMap() {
...
for(var i=0; i<locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
title: locations[i]['fullname'],
map: map
});
...
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('phone: ' + locations[i]['phone']);
infowindow.open(map, marker);
}
})(marker, i));
}
...
}
</script>

Geocoding by extracting location from MySQL via PHP

I have written the following PHP script to get the value from MySQL database:
<?php
$user="root";
$password="password";
$dbh = new PDO("mysql:host=localhost;dbname=muzicmap", $user, $password);
$sql = "SELECT DISTINCT (
`name`
) AS `name` , `id` , `location` , `background` , `genre` , `current_members` , `website` , `image` , `lonlat`
FROM `artist`
WHERE `location` LIKE '%Los Angeles%'
LIMIT 10
";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
foreach ($result as $row){
$return[]=array('id' => $row['id'],'name'=>$row['name'],'location'=> $row['location'],'background' => $row['background'], 'genre' => $row['genre'],'current_members'=>$row['current_members'],'website' => $row['website']);
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
Now I have made a page in which I want to achieve 3 things:
1. Geocode the location in the location field of my json.
2. Put markers on google maps.
3. Make a drawable type object after doing this all.
So I wrote the following:
markers= []
var geocoder;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.2859268188,-75.9843826294)
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.CIRCLE,
]
},
circleOptions: {
fillColor: '#FFFF00',
fillOpacity: 0,
strokeWeight: 1,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
var IDs=[];
for(var k in markers){
if(google.maps.geometry.spherical
.computeDistanceBetween(circle.getCenter(),markers[k].getPosition())
<=circle.getRadius()){
IDs.push(k);
}
}
});
$(function ()
{
$.ajax({
url: 'jsonTest.php', //the script to call to get data
data: "",
dataType: 'json',
success: function(data)
{
adMarker(map, data);
}
});
});
}
function adMarker(map,json1){
geocoder= new google.maps.Geocoder();
for (var i = 0; i < (json1.length); i++) {
geocoder.geocode({'address':json1[i]['location']},function(results,status){
if (status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: json1[i]['names'],
zIndex: json1[i]['id']
});
markers.push(marker);
}else {
alert("Something wrong");
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
I am not getting the desired result where the markers are put on the map after geocoding. When I debug it I see that the code snipet which is supposed to geocode and create the marker is not run in the for iteration. Why is that? I am new to javascript I would really appreciate all the help fixing this.
The error in the debugger though,says:
InvalidValueError: setZIndex: not a number
I solved the problem.
Because there is an asynchronous call in the adMarker(). I made a function so that copies of that function are made on each for iteration as the asynchronous call will run only after the iteration is complete. This way all the iteration with copies will run. Updated code:
function adMarker(map,json1){
geocoder= new google.maps.Geocoder();
for (var i = 0; i < (json1.length); i++) {
abc(i, json1, map);
}
}
function abc (index, json1, map){
var current_index = index;
geocoder.geocode({'address':json1[index]['location']},function(results,status){
if (status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: json1[index]['names'],
zIndex: parseInt(json1[index]['id'])
});
markers.push(marker);
}else {
alert("Something wrong");
}
});
}

How to assign php variable to javascript variable

<?php
$query = mysql_query("SELECT products_zipcode FROM products ")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$zip = $row['products_zipcode'];
}
?>
here how to assign $zip variable value to java script variable var address = zip;
<script type="text/javascript">
function codeAddress(zip) {
var address = zip;
geocoder.geocode( { 'address': 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
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
</script >
Here changed the code
as
per the answers
<?php
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("coachup_db1") or die(mysql_error());
?>
<?php
$query = mysql_query("SELECT products_zipcode FROM products ")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$zip[] = $row['products_zipcode'];
// echo("codeAddress($zip)");
}
?>
<div id="map-canvas"></div>
<style>
#map-canvas {
width: 300px;
height: 200px;
margin: 0px;
padding: 0px;
border: 0px; padding: 0px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 4,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = <?php echo json_encode($zip); ?>;
var overallcontent = <?php echo json_encode($zip); ?>;
geocoder.geocode( { 'address': 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
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', codeAddress);
</script>
you can assign a php variable to a javascript variable using the following method.
var address =<?php echo json_encode($zip) ?>;
on the other hand if you want to assign a php array to a javascript variable than:
var overallcontent = <?php echo json_encode($type); ?>;
where $type is a php array.
var address = "<?php echo $zip ?>";
Simply echo it and store it in a JavaScript variable. Here's how:
var address = "<?php echo $zipCode' ?>";

Categories