How to assign php variable to javascript variable - javascript

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

Related

using mysql and php with google maps

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>

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>

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>

How to Add Google Map in website using mysql

I am doing this first time, how can I add google map in my website? I have done AJAX please see this code and give me answer
The area that comes throw database using AJAX, Area are perfectly done and "latitude" & "longitude" are perfectly got it, but I can't use that latitude & longitude in JavaScript code.
this is my php file code is:
<div class="col-lg-4">
<select name="area_id" class="form-control" onchange="showUser(this.value)" id="area">
<option value="">Select Area</option>
</select>
</div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</div>
<div id="txtHint"><b>Person info will be listed here...</b></div>
this is getuser.php file:
<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=" My Map Key "&callback=initMap"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style>
#txtHint {
height: 350px;
}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
echo $sql = "SELECT * FROM area WHERE area_id='$q'";
$qry = mysql_query($sql);
while($fetch = mysql_fetch_array($qry))
{
$area_name=$fetch['area_name'];
//$city_name=$fetch['city_name'];
$address =$area_name; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$area_latitude = $output->results[0]->geometry->location->lat;
$area_longitude = $output->results[0]->geometry->location->lng;
echo "<br><input type='text' name='area_latitude' id='area_latitude'value='".$area_latitude."'> <br>";
echo "<input type='text' name='area_longitude' id='area_longitude' value='".$area_longitude."'>";
?>
<script type="text/javascript">
var map;
var marker;
var area_latitude = $("#area_latitude").val();
var area_longitude = $("#area_longitude").val();
var myLatlng = new google.maps.LatLng(area_latitude, area_longitude);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("txtHint"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({
'latLng': myLatlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function () {
geocoder.geocode({
'latLng': marker.getPosition()
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<?php }
?>
</body>
</html>
The values being returned by this are probably strings ("1.2345") instead of Floats (1.2345), which is what the Google Maps expects for coordinates:
var area_latitude = $("#area_latitude").val();
var area_longitude = $("#area_longitude").val();
Try:
var area_latitude = parseFloat($("#area_latitude").val());
var area_longitude = parseFloat($("#area_longitude").val());

display marker on google map after fetching data from database

I have a script(get_search_data.php) that performs search from the database based on the keyword fname. i wish that according to the search result, locations should get displayed on the map (display_map.php) along with the marker and popup window for information.
table view for features_for_office
id fname co_address_line1 co_address_line2 lat lon
get_search_data.php
<?php
require 'config.php';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$fname = $_POST['fname'];
$sth = "SELECT * FROM features_for_office WHERE fname LIKE :fname ";
$stmt = $db->prepare($sth);
$stmt->bindValue(':fname', '%' . $fname . '%', PDO::PARAM_STR);
$stmt->execute();
$locations = $stmt->fetchAll();
echo json_encode( $locations );
} catch (Exception $e) {
echo $e->getMessage();
}
?>
<script src="jquery-1.11.1.js"></script>
<script>
$(document).ready(function(){
$('#drop2').on('change',function(){
//var fname = $(this).val();
var fname = $(this).find('option:selected').text();
// rename your file which include $fname with get_search_data.php
if(fname !== ""){
$.post('display_map.php',{fname: fname},function(data){
$('.showsearch').html(data);
});
}
});
});
</script>
display_map.php
<style type="text/css">
#main { padding-right: 15px; }
.infoWindow { width: 220px; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function makeRequest(url, callback)
{
var request;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
}
else
{
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
// Ban Jelačić Square - City Center
var center = new google.maps.LatLng(21.0000, 78.0000);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init()
{
var mapOptions =
{
zoom: 6,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
makeRequest('get_search_data.php', function(data)
{
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++)
{
displayLocation(data[i]);
}
});
}
function displayLocation(location)
{
var content = '<div class="infoWindow"><strong>' + location.fname + '</strong>'
+ '<br/>' + location.co_address_line1
+ '<br/>' + location.co_address_line2 + '</div>';
if (parseInt(location.lat) == 0)
{
geocoder.geocode( { 'address': location.co_address_line1 }, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var marker = new google.maps.Marker
({
map: map,
position: results[0].geometry.location,
title: location.name
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
});
}
else
{
var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lon));
var marker = new google.maps.Marker
({
map: map,
position: position,
title: location.name
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
}
</script>
</head>
<body onload="init();">
<section id="main">
<div id="map_canvas" style="width: 70%; height: 500px;"></div>
</section>
</body>
Although the map gets displayed but the markers are not getting displayed. would appreciate any help
It might be strange answer, but your code should work.
But if you mix up lat and lon in your database markers would still display but you won't see them because they appear in another part of the world.
If I am wrong please post the the structure of json response from php script

Categories