Creating multiple instances of a google API on an HTML page

Go To StackoverFlow.com

0

I am creating a web page that lets a user enter a start location and an end location into textbox's and the distance between the two locations is output (this is using a google API). I have successfully been able to create a single instance of this that works as I want it to. However my problem is that I need multiple rows of this but as soon I duplicate the code I cannot seem to get it to work. This is my first real attempt at using javascript so my understanding of it is not that great. I realise that I need to change variables etc. but am unsure exactly as what to change. Sorry if I have not been clear enough but any help would be great, thanks.

Here is my code:

<body onload="initialize()">

<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var belfast = new google.maps.LatLng(55, -5)
    var myOptions = {
        zoom:5,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: belfast,
    }

    map = new google.maps.Map(document.getElementById("map_canvas1"), myOptions);
        directionsDisplay.setMap(map);
    }

function calcRoute() {
    var start = document.getElementById("pc1").value;
    var end = document.getElementById("pc2").value;

    var distanceInput = document.getElementById("distance");
    var request = {
        origin:start, 
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
            }
        });
    }

<td><input type="text" id="pc1" /></td>

2012-04-04 22:51
by Rosco
do you need multiple routes or multiple waypoints for one route - Michal 2012-04-04 23:06
I would need it for multiple route - Rosco 2012-04-04 23:11


0

If you're creating multiple instances of Google Maps, you need to make sure you're not mixing up global variables. These variables you're declaring on a global level:

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

So if you try to create a second map and assign the map to the map variable, which should destroy the previous map. Likewise your DirectionsService. So you need to create a variable for each of those for each instance.

2012-04-05 00:04
by Mano Marks
thats it working now, thanks very much for your help - Rosco 2012-04-05 15:05
Ads