简体   繁体   English

我的JavaScript拆分功能不起作用

[英]My JavaScript split function not working

I have the following code which through Google Maps API gets the latitude and longitude of the position clicked on the map 我有以下代码,这些代码通过Google Maps API获取在地图上单击的位置的纬度和经度

var latitude_longitude = evt.latLng;

When I alert the variable using the code below the following is displayed: (53.4128,-1.51165) 当我使用下面的代码警告变量时,将显示以下内容:(53.4128,-1.51165)

   alert(latitude_longitude);////Gets latitude and Longitude - Latitude first - Longitude second

However I now need to split (53.4128,-1.51165) into 2 variables Latitude and Longitude and have tried using the code below: 但是我现在需要将(53.4128,-1.51165)分为2个变量纬度和经度,并尝试使用以下代码:

var myarr = latitude_longitude.split(",");
var latitude = myarr[0];
alert(latitude);

However the alert doesn't show and I am unsure why? 但是没有显示警报,我不确定为什么?

你可以试试:

var latitude = evt.latLng.lat();

Given this: 鉴于这种:

var latlng = '53.4128,-1.51165';
console.log(latlng);
var lat = latlng.split(",")[0];
console.log(lat);

I get the output: 我得到的输出:

53.4128,-1.51165
53.4128

So splitting on the comma is perfectly valid for a string variable with a comma in it. 因此,逗号分隔对于其中带有逗号的字符串变量完全有效。 However, I suspect that your latitude_longitude is not a string. 但是,我怀疑您的latitude_longitude不是字符串。 Open Developer Tools (or its equivalent for the browser you are using), set a breakpoint and examine the variable. 打开开发人员工具(或与您使用的浏览器等效的工具),设置一个断点并检查变量。 I suspect you will see that it is an object with properties and that you can just access those properties instead of trying to parse its string representation. 我怀疑您会看到它是一个具有属性的对象,您可以访问这些属性,而不必尝试解析其字符串表示形式。

first check if your variable is an object or string: 首先检查您的变量是对象还是字符串:

 alert(typeof latitude_longitude);

if your alert output is "object" so you need to convert it to string 如果您的警报输出是“对象”,那么您需要将其转换为字符串

var strLatLong=String(latitude_longitude);
var LangLat = strLatLong.split(",");
alert(typeof strLatLong);

....it worked for me ....对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM