本文介绍了通过AJAX获取位置信息后创建地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过AJAX从文本文件中获取位置的经度和纬度,然后使用该信息创建地图.这就是我所做的:

I need to get the longitude and latitude of a location from a text file through AJAX then create a map using that information. This is what I have done:

function createMap(){

var request;

if (window.XMLHttpRequest)
{
    request = new XMLHttpRequest();
}

if (request)
{
    var number = Math.floor( (Math.random() * 3) + 1 );

    var url = "text_" + number + ".txt";

    request.open("GET", url,true);

    request.onreadystatechange = function()
    {
        if (request.readyState == 4 && request.status == 200)
        {
        var syd=new google.maps.LatLng(-33.884183, 151.214944);
        var woll=new google.maps.LatLng(request.responseText);
        function initialize()
        {
            var mapProp = {
                    center:syd,
                    zoom:6,
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                    };

            var map=new google.maps.Map(document.getElementById("outputAJAX"),mapProp);

            var myTrip=[syd,woll];
            var flightPath=new google.maps.Polyline({
                    path:myTrip,
                    strokeColor:"#0000FF",
                    strokeOpacity:0.8,
                    strokeWeight:2
                    });

            flightPath.setMap(map);
        }

            initialize();
        }
    }

    request.send();

} else {

    document.getElementById("outputAJAX").innerHTML = "<span style='font-weight:bold;'>AJAX</span> is not supported by this browser!";
}}

但是,地图没有显示.你们有什么建议吗?

However, the map didn't show up. Do you guys have any suggestion?

推荐答案

A google.maps.LatLng对象以两个 Numbers 作为其参数:

A google.maps.LatLng object takes two Numbers as its arguments:


LatLng(lat:number, lng:number, noWrap?:boolean) Creates a LatLng object representing a geographic point. Latitude is specified in degrees within the range [-90, 90]. Longitude is specified in degrees within the range [-180, 180]. Set noWrap to true to enable values outside of this range. Note the ordering of latitude and longitude.

这行不通(您只传递了一个参数,一个字符串):

This won't work (you are only passing one argument, a string):

var woll=new google.maps.LatLng(request.responseText);

假设request.responseText是一个逗号分隔的字符串,其中包含两个数字值,则应该可以:

Assuming request.responseText is a comma separated string containing two numeric values, this should work:

var coordStr = request.responseText;
var coords = coordStr.split(",");
var woll = new google.maps.LatLng(parseFloat(coords[0]),
                                  parseFloat(coords[1]));

概念证明小提琴

这篇关于通过AJAX获取位置信息后创建地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 22:35