5

I want to show google map on popover

But the popover fails to change map

Only works when the map is fixed

My code :

$(function(){

// getmap function from http://stackoverflow.com/questions/10545768/google-map-in-twitter-bootstrap-popver
var getMap = function(opts) {
  var src = "http://maps.googleapis.com/maps/api/staticmap?",
  params = $.extend({
    center: 'New York, NY',
    zoom: 14,
    size: '512x512',
    maptype: 'roadmap',
    sensor: false
  }, opts),
  query = [];

  $.each(params, function(k, v) {
query.push(k + '=' + encodeURIComponent(v));
  });

  src += query.join('&');
  return '<img src="' + src + '" />';
}



$('.map').click(function(){
    location = $(this).text();
    $("#map").html(getMap({center: location}));
    });


$('.map').popover({trigger:'click',placement:'left',html:true,content:function(){
    return $("#map").html();
    }});    

    });

My problem with this function :

$('.map').click(function(){...});

With Click on the link(.map) because the #map is changed, the popover is broken and does not work

Thank you

ali smith
  • 93
  • 2
  • 2
  • 9

1 Answers1

17

I don't think you need to do it in two separate steps (click then popover), nor do you need the div unless there's some reason for that which you haven't mentioned. This works for me:

JavaScript:

$('.map').popover({trigger:'click',placement:'left',html:true,content:function(){
     return getMap({center: $(this).text()})
  }});    
});

You can then remove the center: 'New York, NY', line from your getMap params.

HTML:

<a href="#" class="map">New York, NY</a>

If you were using the #map div to make the popover larger, just change the CSS of the popover instead, by doing something like:

.popover { width: 512px; height: 512px; }

I would recommend using a more specific selector for that though, otherwise it will affect popovers elsewhere on your site.

frostyterrier
  • 1,912
  • 1
  • 15
  • 16
  • I've already tried this method: ` `$('.map').popover({...,content:function(){ return getMap({center: $(this).text()}) }}); });` but only works when the map is fixed, getMap({center: $(this).text()}) means the content will change with every click – ali smith Mar 16 '13 at 05:38
  • This code works well, The problem I had with location variable!! – ali smith Mar 16 '13 at 06:08
  • 1
    Yeah, location is not a good variable to use with JavaScript because some browsers will interpret it as you wanting to go to that URL. I'm glad you got it working though. – frostyterrier Mar 16 '13 at 10:01
  • This answer didn't work for me, but this did: http://stackoverflow.com/a/19684440/482115 – degenerate May 12 '15 at 19:28