Craig
Craig

Reputation: 325

Can't seem to pass JS argument (variable) to Google Map API v3 function

I'm attempting to move a large block of Google Maps API script off of the page and into an included .js file.

But! In order to do that I've got to tweak the function to accept passed variables.

Here's the start of the script normally...

<script type="text/javascript">
//<![CDATA[
function loadGmap() {
  var map1options = {
    center: new google.maps.LatLng(-12.043333,-77.028333),
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    zoom: 4,
    minZoom: 2,
    streetViewControl: false
  };

and here's me try to pass the first variable (and failing)...

<script type="text/javascript">
//<![CDATA[
function loadGmaps() {
  loadGmap('-12.043333,-77.028333');
}

function loadGmap(coordinates) {
  var map1options = {
    center: new google.maps.LatLng(coordinates),
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    zoom: 4,
    minZoom: 2,
    streetViewControl: false
  };

Ideas? Maybe this shouldn't be a string... or something?

Upvotes: 0

Views: 1474

Answers (4)

Elias Echeverri
Elias Echeverri

Reputation: 31

As of recent you need to CAST the LatLng variables as follows:

buildinglatlng = new google.maps.LatLng(Number(maplatitude), Number(maplongitude));

Upvotes: 0

Torsten Becker
Torsten Becker

Reputation: 4323

Change to this line:

center: new google.maps.LatLng(
  parseFloat(coordinates.split(",")[0]), 
  parseFloat(coordinates.split(",")[1])
),   

Upvotes: 1

rid
rid

Reputation: 63442

You need to pass the same arguments... That method accepts 2 arguments: latitude and longitude, not a single string argument.

function loadGmaps() {
    loadGmap(-12.043333, -77.028333);
}

function loadGmap(lat, long) {
    var map1options = {
        center: new google.maps.LatLng(lat, long),
        ...

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237817

center: new google.maps.LatLng(-12.043333,-77.028333),

There you pass two arguments to LatLng. In your new function, you still need to pass two arguments to LatLng. The easiest way to do this is to accept two arguments to your function:

function loadGmaps() {
    loadGmap(-12.043333,-77.028333);
}

function loadGmap(lat, lng) {
    var map1options = {
        center: new google.maps.LatLng(lat, lng),
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        zoom: 4,
        minZoom: 2,
        streetViewControl: false
    };
}

Upvotes: 3

Related Questions