Anuj TBE
Anuj TBE

Reputation: 9790

Set value from database to JavaScript using php

I have to show google map marker in my website where the value of latitude and longitude is coming from database from latitude and longitude columns.

Initially JavaScript code is

var map;
function initialize() {
    map = new GMaps({
        div: '#map',
        lat: -37.817917,
        lng: 144.965065,
        zoom: 16

    });
    map.addMarker({
        lat: -37.81792,
        lng: 144.96506,
        title: 'Marker with InfoWindow',
        icon: 'images/map-marker.png',
        infoWindow: {
            content: '<p>Melbourne Victoria, 300, Australia</p>'
        }
    });
}

I tried with placing php code as:

lat: <?php echo $latitude; ?>
lng: <?php echo $latitude; ?>

But it doesn't work.

I figure out one more way to do this is set input field value to the coordinates and then call it to JavaScript using getElementById

<input id="map_latitude" value="<?= $latitude ?>" hidden>
<input id="map_longitude" value="<?= $longitude ?>" hidden>

and in JavaScript: (this is just experimental, don't know whether correct or not)

lat: getElementById('#map_latitude'),
lng: getElementById('#map_longitude')

Upvotes: 1

Views: 233

Answers (2)

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

For second option try the below

lat: document.getElementById('map_latitude').value,
lng: document.getElementById('map_longitude').value

Upvotes: 2

Phiter
Phiter

Reputation: 14992

This should totally work:

div: '#map',
lat: <?php echo $latitude; ?>,
lng: <?php echo $longitude; ?>,

The second option should work too but with a little change.

var map;
var lati = getElementById('map_latitude').value;   //Need to select the value
var longi = getElementById('map_longitude').value; //and remove the hashtag ( # )
function initialize() {
    map = new GMaps({
        div: '#map',
        lat: lati,
        lng: longi,
        zoom: 16

Always check your console for errors.

Upvotes: 1

Related Questions