Javascript 将位置坐标作为变量传递给谷歌地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10676828/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:27:54  来源:igfitidea点击:

Passing location coordinates to google maps as variable

javascriptgoogle-mapsgoogle-maps-api-3

提问by coryetzkorn

Anyone know why this will work:

任何人都知道为什么这会起作用:

var wickedLocation =  new google.maps.LatLng(44.767778, -93.2775);

But this won't:

但这不会:

var wickedCoords = "44.767778, -93.2775";
var wickedLocation =  new google.maps.LatLng(wickedCoords);

I tried passing the latitude and longitude as separate variables and that didn't do the trick either. How can I pass the coordinates successfully as a variable? Thanks!

我尝试将纬度和经度作为单独的变量传递,但这也不起作用。如何将坐标作为变量成功传递?谢谢!

回答by jmort253

In this example, you are passing two distinct numerical values into a constructor and then assigning the newly created object to wickedLocation:

在此示例中,您将两个不同的数值传递给构造函数,然后将新创建的对象分配给 wickedLocation:

var wickedLocation =  new google.maps.LatLng(44.767778, -93.2775);

In this example, you're passing a single string value into a constructor that requires two distinct numerical coordinates:

在此示例中,您将单个字符串值传递给需要两个不同数字坐标的构造函数:

var wickedCoords = "44.767778, -93.2775";
var wickedLocation =  new google.maps.LatLng(wickedCoords);

The data types are both completely different.

两者的数据类型完全不同。

With that said, if you want to represent a coordinate as a single object, you can do so like this:

话虽如此,如果您想将坐标表示为单个对象,您可以这样做:

var myHome = { "lat" : "44.767778" , "long" : "-93.2775" };

var yourHome = { "lat" : "23,454545" , "long" : "-92.12121" };

Then when you need to create the coords object from Google, you can pass the data in as individual arguments derived from a single object:

然后,当您需要从 Google 创建 coords 对象时,您可以将数据作为从单个对象派生的单独参数传入:

var wickedLocation =  new google.maps.LatLng( myHome.lat, myHome.long );

回答by dda

If you are getting the coordinates as a string, in the format you showed in your example, you could do this:

如果您以字符串形式获取坐标,则按照您在示例中显示的格式,您可以执行以下操作:

var b=wickedCoords.split(",");
var wickedLocation=new google.maps.LatLng(parseFloat(b[0]), parseFloat(b[1]));

回答by Collin Green

I believe you can use strings to define the coordinates, but you need two (one for each parameter) not one.

我相信您可以使用字符串来定义坐标,但您需要两个(每个参数一个)而不是一个。

wickedLat = '44.767778';
wickedLon = '-93.2775';
wickedLocation = new google.maps.LatLng(wickedLat, wickedLon);

If not either use floats directly or parse your strings into floats with parseFloat()

如果不是直接使用浮点数或将您的字符串解析为浮点数 parseFloat()