0

I have a page with an initial google map (of a city) and a combobox. The user can pick a location by dragging a marker on the map, and then this value (lang, long) is saved to a hidden field and passed to the server. The combo however list some city areas. When a user selects an area, the google map is changed: the city map dissapears and the map of the selected area is displayed. This is done via getJSON, and it all works fine.

My problem is how to enable this second map, the area map, with the same functionality (update the position of the draggable marker). I understand that the listeners are initially bound to the initial map, I just don't know enough javascript to understand where to put these functions to enable the functionality on the new maps, maybe something with jquery live?

I found great help in this answer but it doesn't solve my problem.

The code is the following

<script type="text/javascript" src="/site_media/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

$(function() {

$("#id_area").change(function() {

    var url = '/areageo/'+this.value;

    $.getJSON(url, function(data) {

        if (data.lat){

            $('#mapCanvas').empty();
            // map options
            var options = {
                   zoom: 14,
                   center: new google.maps.LatLng(data.lat, data.lon),
                   mapTypeId: google.maps.MapTypeId.ROADMAP
                 };

                 // Creating the map
            var map = new google.maps.Map(document.getElementById('mapCanvas'), options);

                 // Adding a marker to the map
            var marker = new google.maps.Marker({
                   position: new google.maps.LatLng(data.lat, data.lon),
                   map: map,
                   title: 'Some title',
                   draggable: true,
                      });
            }

                 });  //getJSON end function

    });  //id_area change end function

});


         var geocoder = new google.maps.Geocoder();
         function geocodePosition(pos) {
           geocoder.geocode({
             latLng: pos
           }, function(responses) {
             if (responses && responses.length > 0) {
               updateMarkerAddress(responses[0].formatted_address);
             } else {
               updateMarkerAddress('Cannot determine address at this location.');
             }
           });
         }
         function updateMarkerStatus(str) {
           document.getElementById('markerStatus').innerHTML = str;
         }
         function updateMarkerPosition(latLng) {
           document.getElementById('info').innerHTML = [
             latLng.lat(),
             latLng.lng()
           ].join(', ');

           id_lat.value = [
             latLng.lat()];
           id_lon.value = [
             latLng.lng()];
         }

         function updateMarkerAddress(str) {
           document.getElementById('address').innerHTML = str;
         }

        // initial setup
         function initialize() {
           var latLng = new google.maps.LatLng(44.77184334415235, 20.55164378320319); // initial map position
           var map = new google.maps.Map(document.getElementById('mapCanvas'), {
             zoom: 12, // initial zoom
             center: latLng,
             mapTypeId: google.maps.MapTypeId.ROADMAP
           });

           var marker = new google.maps.Marker({
             position: latLng,
             title: 'Point A',
             map: map,
             draggable: true,

           });

           // Update current position info.
           updateMarkerPosition(latLng);
           geocodePosition(latLng);

           // Add dragging event listeners.
           google.maps.event.addListener(marker, 'dragstart', function() {
             updateMarkerAddress('Dragging...');
           });

           google.maps.event.addListener(marker, 'drag', function() {
             updateMarkerStatus('Dragging...');
             updateMarkerPosition(marker.getPosition());
           });

           google.maps.event.addListener(marker, 'dragend', function() {
             updateMarkerStatus('Drag ended');
             geocodePosition(marker.getPosition());
           });
         }


         // Onload handler to fire off the app.
         google.maps.event.addDomListener(window, 'load', initialize);
         </script>

1 Answer 1

1

The easy answer is Don't get rid of the map. When the user selects a suburb, zoom the existing map to that area (and move the marker if necessary so it's visible). Then you don't have to redefine anything.

If you have a map, try to do everything with that one map. You should never have to destroy it: just get it to show something else.

So your if (data.lat) {... block only needs to centre the map on data.lat,data.lon and move the existing marker to that location. Because the marker is still the same marker, and the map is still the same map, you don't need to recreate listeners or anything.

Sign up to request clarification or add additional context in comments.

4 Comments

this sounds very good and logical, I just use the same map and dynamically change it?
excuse me, just one more question, is my initial map visible to the outside code if I declare it with function initialize() { var latLng = new google.maps.LatLng(44.77184,20.55164); var map = new google.maps.Map(document.getElementById('mapCanvas'), { ...
If var map occurs inside a function, it's local to that function and not available elsewhere. Use var map; in global scope (outside any function) and then assign the Map object to that with map = new google.maps.Map(...); inside a function.
Yep. I got it - removed the var and it's all good. Thank you very very much Andrew, you saved me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.