开发者

I need help with jQuery and the Google Maps API

I'm trying to learn the Google Maps and Places API, so I thought I'd get started with the basics: displaying the user's location on a map via their IP address.

I found a jQuery script in another thread which gets the user's latitude and longitude and it works fine (an alert placed below the var displays the latitude and longitude), but when I pass the variable to the Maps method, it doesn't work. Can someone see anything wrong with my function or how it's being called?

$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {  
var latlng = new google.maps.LatLng(data.latitude,data.longitude);  
function initialize() {  
    var myOptions = {  
      zoom: 8,  
      center: latlng,  
      mapTypeId: google.maps.MapTypeId.ROADMAP  
    };  
    var map = new google.maps.Map(document.getElementById("map_canvas"),  
        myOptions);  
    }  
});

EDIT: By the way, these are the scripts that I'm using:

<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>  
<script language="javascript" src="http://maps.goo开发者_开发技巧gle.com/maps/api/js?sensor=false"></script>


I think I know what you did there. Looks like you are using the Hello World gmaps example to start with.

If you notice the gmaps example calls the initialize function on onload of the map element, so what you want to do is put contents of the getJSON() call inside of the initialize function wrapping the original code of that function.

Here is how it looks:

function initialize() {  

    $.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {  
        var latlng = new google.maps.LatLng(data.latitude,data.longitude);  
        var myOptions = {  
            zoom: 8,  
            center: latlng,  
            mapTypeId: google.maps.MapTypeId.ROADMAP  
        };  
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    });

}


Try to declare your function initialize() outside the return block of getJSON.

Like this:

$(function(){

    $.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {  
            var latlng = new google.maps.LatLng(data.latitude,data.longitude);  
            initialize(latlng);
    });
});

function initialize(latlng) {  
    var myOptions = {  
      zoom: 8,  
      center: latlng,  
      mapTypeId: google.maps.MapTypeId.ROADMAP  
    };  
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);  
}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜