Anecito Alima Santillan Anecito Alima Santillan - 1 month ago 15
PHP Question

creating a google map that is connected to database

I am trying to create a google map. the latitude and the longitude are from the database so I had to put those in a textbox then get its value in the script. I tried doing so but it doesn't work will you help me with this one; here's my JavaScript:

function initMap() {

var lat = document.getElementById('lat');
var lang = document.getElementById('lang');

var uluru = {lat: lat, lng: lang };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}


Here's the html:

<input type="text" style="display: none" id="lat" value="7.8383054" />
<input type="text" style="display: none" id="lang" value="123.2966657" />

<div id="map" ">
</div>


JSfiddle

Answer
  1. the "numbers" in the text fields are access using the .value property:
  2. the lat/lng in a google.maps.LatLngLiteral must be numbers. (without the parseFloat the API throws these errors:
    • InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
    • InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
var lat = parseFloat(document.getElementById('lat').value);
var lang = parseFloat(document.getElementById('lang').value);
  1. You need to actually call the initMap method (your fiddle isn't doing this)

updated fiddle

code snippet:

html,
body,
#map {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<input type="text" id="lat" value="7.8383054" />
<input type="text" id="lang" value="123.2966657" />

<div id="map" ">
</div>
<script>
function initMap() {

        var lat = parseFloat(document.getElementById('lat').value);
        var lang = parseFloat(document.getElementById('lang').value);

    var uluru = {lat: lat, lng: lang };
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: uluru
    });
    var marker = new google.maps.Marker({
        position: uluru,
        map: map
    });
}
</script>

Comments