javascript 使用谷歌地图api的经度和纬度变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30983768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using variables for longitude and latitude with google maps api
提问by Mr.Smithyyy
I've just started using the google maps API for browsers but I can't seem to get it to work when I place variables in the longitude/latitude places instead of numbers directly.
我刚刚开始在浏览器上使用谷歌地图 API,但是当我将变量直接放在经度/纬度位置而不是数字时,我似乎无法让它工作。
I need the maps to populate from the value of two input elements.
我需要从两个输入元素的值填充地图。
It doesn't work with variables but if you change the variables in the function to numbers it works perfectly.
它不适用于变量,但如果您将函数中的变量更改为数字,则它可以完美运行。
Yes I'm aware I shouldn't post my API key but this is one I use on an off account for testing and I will end up deleting it.
是的,我知道我不应该发布我的 API 密钥,但这是我在关闭帐户上用于测试的密钥,我最终会删除它。
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>
回答by n00dl3
You are using strings, please try with floats:
您正在使用字符串,请尝试使用浮点数:
var userLng = parseFloat($('#lng').val());
var userLat = parseFloat($('#lat').val());
var mapOptions = {
center: { lat: userLat, lng: userLng },
zoom: 8
};
回答by Griva
You shuld parseFloat() your input values, you need numbers not string.
你应该 parseFloat() 你的输入值,你需要数字而不是字符串。
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>
Edit, sr parseFloat not parseInt
编辑,sr parseFloat 不是 parseInt