Using variables for longitude and latitude using google maps api

I just started using the google maps API for browsers, but I can't get it to work when I put variables in longitude / latitude places instead of direct ones.

I need cards to populate out the value of two input elements.

It does not work with variables, but if you change variables in functions to numbers, this works fine.

Yes, I know that I should not publish my API key, but this is the one I use in the disconnected account for testing, and I will eventually delete it.

function initialize() { var userLng = $('#lng').val(); var userLat = $('#lat').val(); var mapOptions = { center: { lat: userLat, lng: userLng }, zoom: 8 }; var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); } google.maps.event.addDomListener(window, 'load', initialize); 
 #map-canvas { height: 30em; width: 30em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCgxY6DqJ4TxnRfKjlZR8SfLSQRtOSTxEU"></script> <form> <input type="text" id="lng" name="lng" value="30"> <input type="text" id="lat" name="lat" value="40"> </form> <div id="map-canvas"></div> 
+5
source share
2 answers

You use strings, try with floats:

 var userLng = parseFloat($('#lng').val()); var userLat = parseFloat($('#lat').val()); var mapOptions = { center: { lat: userLat, lng: userLng }, zoom: 8 }; 
+10
source

You shuld parseFloat () your input values, you need digits not strings.

 function initialize() { var userLng = parseFloat($('#lng').val()); var userLat = parseFloat($('#lat').val()); var mapOptions = { center: { lat: userLat, lng: userLng }, zoom: 8 }; var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); } google.maps.event.addDomListener(window, 'load', initialize); 
 #map-canvas { height: 30em; width: 30em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCgxY6DqJ4TxnRfKjlZR8SfLSQRtOSTxEU"></script> <form> <input type="text" id="lng" name="lng" value="30"> <input type="text" id="lat" name="lat" value="40"> </form> <div id="map-canvas"></div> 

Change sr parseFloat not parseInt

+2
source

All Articles