2

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.google.com/maps/api/js?sensor=false"></script>
Community
  • 1
  • 1
Davenport
  • 219
  • 3
  • 9
  • Stupid question, but do you have an element with the id `map_canvas` on the page that you've embedded this script in? – casperOne May 06 '11 at 19:48
  • Just a side note until you answer the above, but why are you using that old jquery? Jquery is at 1.6 now. – plebksig May 06 '11 at 19:50

2 Answers2

0

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);
    });

}
Anton
  • 12,285
  • 20
  • 64
  • 84
0

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);  
}  
Tulio
  • 955
  • 6
  • 12