flavordaaave flavordaaave - 4 days ago 5
AngularJS Question

Custom Pushpin with Angular directive content on a Bing Maps

I'm using the Bing Maps AJAX Control to display a map.
And I've created an Angular directive for the Pushpins I'd like to put on the map:

app.directive('myPin', function(){
return {
restrict: 'E',
templateUrl: '<p>{{title}}</p>'
}
})


within my Angular controller, I set up the map and then add (a) Pin(s) to it like this:

// Define the title for the Pin
$scope.title = 'Test title';

// Define the location and the options for the Pin
var location = new Microsoft.Maps.Location(52.48, 13.42);
var pushpinOptions = {
width: null,
height: null,
htmlContent: '<my-pin></my-pin>'
};

// Push the Pin onto the map
map.entities.push(new Microsoft.Maps.Pushpin(location, pushpinOptions));


Unfortunately, but obviously as well, my custom pin is not showing up on the map because the piece of "htmlContent" is injected dynamically to the DOM by the Bing service. I've tried a lot with Angular's $compile service but I couldn't figure out how to get it working...

Answer

I managed to get this working for an infobox, I imagine it would work the same with the pushpin. Please note, this is a rough working copy and will need further work to make it nicer. It's almost entirely done in about as far from the angular way as possible. I thought I'd share seeing as no one had managed to answer it in a way that worked for me yet.

I did it in two steps: Set the htmlContent to an empty div with an ID:

Mark up templates:

<div id="infoBox" style="display: none"><div id="infoboxText"></div></div>
<div id="infoBoxContents" style="display: none;"><b id="infoboxTitle" ng-bind="vm.searchResult"></b><p id="infoboxDescription">Select this address as the correct address? <button ng-click="vm.selectAddress()">Yes!</button></p></div>

Controller "search success function"

this.searchSuccess = function (geocodeResult, userData) {
    ...
    this.map.entities.clear(); //remove existing infoboxes from the map
    var template = $('#infoBox').html(); //<div id="infoboxText"></div>
    var pin = new Microsoft.Maps.Pushpin(location, { draggable: false });
    var infoboxOptions = {
        pushpin: pin
    };
    var defaultInfobox = new Microsoft.Maps.Infobox(_this.map.getCenter(), infoboxOptions);
    defaultInfobox.setHtmlContent(template);
    this.map.entities.push(defaultInfobox); //add it to the map
    this.addContentToInfobox();
}

this.addContentToInfobox = function() {
    var rawContentHtml = $('#infoBoxContents').html();
    $("#infoboxText").html(_this.$compile(rawContentHtml)(_this.$scope));
    this.$scope.$apply();
}

FIDDLE: (requires an API key): http://jsfiddle.net/KyleMuir/m9ato59v/

Comments