center map if id #clicked in the looped - javascript

I have a two components. first one is for the articles content that I am looping. And second one is google map for the articles addresses... They are connected in store.js. No problem with that. And I am trying to center the map to if any articles's id clicked in component one. But having some problems about how to implement clicked event to google map component's listener?
What I thought, using event bus for the situation. And send which "id" clicked.
UPDATED
articles component
<table>
<tbody>
<tr :key="item.id" v-for="item in articles" #clicked="changeCenter(item.id)">
<th>
<img :src="item.image" alt="">
</th>
<td>
<p>{{item.name}}</p>
<p>{{item.address.substr(0,40)}}...</p>
</td>
<td>
<router-link :to="{ name: 'detail', params: {id:item.id} }"><i class="fas fa-chevron-right"></i></router-link>
</td>
</tr>
</tbody>
</table>
And add the method.
methods: {
changeCenter(id){
eventBus.$emit("centerMap", id);
},
},
and on the other side google map component is below.
in created() hook I am catching the id that clicked. But I can't access the value inside the buildMarkers() function. I mean I can console.log(this.centerid) in created() hook there is no problem. I can see the data that I am passing. But when the time come to put the this.centerid in the buildMarkers() or any other methods, centerid is start to being undefined
created(){
eventBus.$on("centerMap", (id) => {
this.centerid = id;
})
},
and rest is a a bit mistery to me. google map code is right below.
data(){
return {
markers:[],
infoWindows: [],
centerid: "",
};
},
mounted(){
this.initMap();
this.clearMarkers();
this.buildMarkers();
},
created(){
eventBus.$on("centerMap", (id) => {
this.centerid = id;
})
},
watch: {
articles(){
this.clearMarkers();
this.buildMarkers();
}
},
methods: {
initMap(){
const japan = {
lat: 35.652832,
lng: 139.839478
}
this.map = new google.maps.Map(document.getElementById("map"), {
zoom: 7,
// maxZoom: 10,
center: {lat: japan.lat, lng: japan.lng}
})
},
buildMarkers(){
var map = this.map;
this.markers = [];
for(var i = 0; i < this.articles.length; i++){
// some codes...
// some codes...
var marker = new MarkerWithLabel({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 0
},
position: position,
map: this.map,
labelClass: "markerClass",
labelAnchor: new google.maps.Point(30, 30),
labelContent: label,
});
this.markers.push(marker);
if (this.articles[i].id === this.centerid) {
google.maps.event.addListener(marker, function () {
infowindow.open(map, this);
map.setCenter(this.getPosition());
map.setZoom(10);
});
}
}
},
clearMarkers(){
for( var i = 0; i < this.markers.length; i++ ){
this.markers[i].setMap( null );
}
},
},
The problem is at this part. I am not sure how to handle this. Like I said before. I can't access the centeridto 's value.
if (this.articles[i].id === this.centerid) {
google.maps.event.addListener(marker, function () {
infowindow.open(map, this);
map.setCenter(this.getPosition());
map.setZoom(10);
});
}

Related

VueJS: Google Maps loads before data is ready - how to make it wait? (Nuxt)

This is my first VueJS project and I've got vue2-google-maps up and running but I've come across an issue when I attempt to connect the map markers to my site's JSON feed (using the Wordpress REST API), the Lat and Lng values are returning undefined or NaN.
On further investigation (thanks to #QuỳnhNguyễn below) it seems like the Google Maps instance is being run before the data is ready. I have tried watching for the feed to be loaded before initialising the map, but it doesn't seem to work.
The marker locations are pulled in from the WordPress REST API using JSON and exist in an array (locations). The array is present and populated in Vue Dev Tools (51 records), but when checking on mounted, the array is empty. The data is pulled in at the created stage, so I don't know why it wouldn't be ready by the mounted stage.
The code in question is as below...
Template:
<template>
<gmap-map v-if="feedLoaded" ref="map" :center="center" :zoom="zoom" :map-type-id="mapTypeId" :options="options">
<gmap-marker
:key="index" v-for="(m, index) in locations"
:position="{ lat: parseFloat(m.place_latitude), lng: parseFloat(m.place_longitude) }"
#click="toggleInfoWindow(m,index)"
:icon="mapIconDestination">
</gmap-marker>
<gmap-info-window></gmap-info-window>
</gmap-map>
</template>
Script
<script>
const axios = require('axios');
const feedURL = "API_REF";
export default {
props: {
centerRef: {
type: Object,
default: function() {
return { lat: -20.646378400026226, lng: 116.80669825605469 }
}
},
zoomVal: {
type: Number,
default: function() {
return 11
}
}
},
data: function() {
return {
feedLoaded: false,
zoom: this.zoomVal,
center: this.centerRef,
options: {
mapTypeControl: false,
streetViewControl: false,
},
mapTypeId: 'styledMapType',
mapIconDestination: '/images/map-pin_destination.png',
mapIconActivity: '/images/map-pin_activity.png',
mapIconAccommodation: '/images/map-pin_accommodation.png',
mapIconEvent: '/images/map-pin_event.png',
mapIconBusiness: '/images/map-pin_business.png',
locations: [],
markers: []
}
},
created: function() {
this.getData();
},
mounted: function() {
this.$nextTick(() => {
this.$refs.karrathaMap.$mapPromise.then((map) => {
var styledMapType = new google.maps.StyledMapType(
[...MAP_STYLE SETTINGS...]
)
map.mapTypes.set('styled_map', styledMapType);
map.setMapTypeId('styled_map');
})
});
},
watch: {
feedLoaded: function() {
if (this.feedLoaded == true) {
console.log(JSON.stringify(this.locations))
}
}
},
methods: {
getData() {
const url = feedURL;
axios
.get(url)
.then((response) => {this.locations = response.data;})
.then(this.feedLoaded = true)
.catch( error => { console.log(error); }
);
}
}
}
</script>
It turns out the issue was dirty data.
The JSON response was including locations that were not supposed to be included on the map, so it failed every time it came across an entry that didn't include the ACF fields, despite me setting the feed to only return data where include on map was true.
I have solved the issue by handling the data once the feed is loaded and creating a new array (markers) from it using the valid data, then using this, rather than the original (locations) array to place the markers on the map.
Cleaning the data:
watch: {
feedLoaded: function() {
if (this.feedLoaded == true) {
var LocationList = this.locations;
for (var i = 0; i < LocationList.length; i++) {
var includeOnMap = LocationList[i].acf['place_include-on-map'];
if (includeOnMap === true) {
var placeName = LocationList[i].title.rendered;
var placeDescription = LocationList[i].acf['place_short-description'];
var placeLatitude = LocationList[i].acf['place_latitude'];
var placeLongitude = LocationList[i].acf['place_longitude'];
var placeIcon = this.mapIconDestination;
this.markers.push({ name: placeName, lat: placeLatitude, lng: placeLongitude, icon: placeIcon });
}
}
}
}
}
Then, the gmap component:
<gmap-map ref="karrathaMap" :center="center" :zoom="zoom" :map-type-id="mapTypeId" :options="options">
<gmap-marker v-if="feedLoaded == true" :key="index" v-for="(m, index) in markers" :position="{ lat: parseFloat(m.lat), lng: parseFloat(m.lng) }" #click="toggleInfoWindow(m,index)" :icon="m.icon"></gmap-marker>
<gmap-info-window></gmap-info-window>
</gmap-map>
Thank you everybody who contributed to helping me get to the bottom of the issue. I will now spend some time rethinking how the data is structured.
It appears to be related with data format. According to vue-devtools from provided screenshot your data is returned from WordPress REST API in the following format:
[
{
"acf": {
"place_latitude": "-22.695754",
"place_longitude": "118.269081",
"place_short-description": "Karijini National Park"
},
"id": 12,
"parent": 10,
"title": {
"rendered": "Karijini National Park"
}
},
...
]
Having how locations array is getting initialized (getData method), position property could be passed like this:
<gmap-marker
:key="index"
v-for="(m, index) in locations"
:position="{ lat: parseFloat(m.acf.place_latitude), lng: parseFloat(m.acf.place_longitude) }"
></gmap-marker>
Here is a demo
vuejs supports v-if directive on elements. I recommend you try as following code snippet.
<template>
<div id="map" v-if="loaded">
<gmap-map ref="map" :center="center" :zoom="zoom" :map-type-id="mapTypeId" :options="options">
<gmap-marker
:key="index" v-for="(m, index) in locations"
:position="{ lat: parseFloat(m.place_latitude), lng: parseFloat(m.place_longitude) }"
#click="toggleInfoWindow(m,index)"
:icon="mapIconDestination">
</gmap-marker>
<gmap-info-window></gmap-info-window>
</gmap-map>
</div>
</template>
<script>
export default {
data() {
return {
loaded: false
}
},
beforeMount: function () {
const url = feedURL;
axios
.get(url)
.then((response) => {
this.locations = response.data;
//activate element after api call response recieved
this.loaded = true
})
.catch(error => {
console.log(error);
}
);
}
}
</script>

How to apply JSON responseText to Google Maps in Ruby on Rails?

So in my Rails app I am building out a region show page with multiple locations. Users are able to insert new locations and map markers need to be dynamically placed based on the latitude and longitude that they enter. In my Region show page I have the following:
<div class="container-fluid">
<div class="row">
<div class="banner" id="region-banner" data-region-name="<%=#region.name.downcase%>">
<script>document.addEventListener('DOMContentLoaded',app.regions);</script>
Then in my region.js file I have the following:
import { tns } from 'tiny-slider/src/tiny-slider.module';
import { mapStyle } from './styles/mapStyle';
app.regions = () => {
function init() {
startGoogleMap();
}
let startGoogleMap = () => {
let map = new google.maps.Map(document.getElementById('region-banner'), {
zoom: 3,
minZoom: 3,
disableDefaultUI: true,
gestureHandling: 'cooperative',
styles: mapStyle
});
var mapElement = document.getElementById('region-banner');
const regionName = mapElement.getAttribute('data-region-name');
let bounds = new google.maps.LatLngBounds();
let promise = $.getJSON('/locations.json');
promise.done(function(data) {
return $.each(data, function() {
return new google.maps.Marker({
position: {
lat: parseFloat(data.lat),
lng: parseFloat(data.lng) },
map: map,
icon: "/marker.png"
});
});
});
console.log(promise);
map.fitBounds(bounds);
};
return init();
};
Then in my controller I have:
def show
#locations = Location.all
respond_to do |format|
format.json { render json: #locations }
format.html
end
end
So no real errors are applying however...nothing appears. The console shows the responseText:“[{“id”: 5, “name”: “Chicago”, “abbreviation”: “CHI”, “lat”: “44.222”, “lng”: “-22.111”}, {“id”: 6, “name”: “Frankfort”, “abbreviation”: “FKT”, “lat”: “41.3232”, “lng”: “-19.5221”} ]”. Which really on this page I should only need/use the first.
Shouldn't it also be applying the markers at this stage since I put in the position?
this is the code responsible for setting your Markers.
I would focus on understanding why promise.done() does not run create the new google.maps.Marker() for each row in your (data) from your response.
Maybe the problem is connected to the /marker.png
promise.done(function(data) {
return $.each(data, function() {
return new google.maps.Marker({
position: {
lat: parseFloat(data.lat),
lng: parseFloat(data.lng) },
map: map,
icon: "/marker.png"
});
});
});

Google Maps Api v3 - several Marker hovers with Javascript

I want to set different hovers for different marker icons i use on my map.
This is my marker icon array
//Marker Icons
var markerIcon = {
unvisitedMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(15, 15)
},
unvisitedMarkerHover: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(30, 0),
anchor: new google.maps.Point(15, 15)
},
activeMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(60, 0),
anchor: new google.maps.Point(15, 15)
},
visitedMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(90, 0),
anchor: new google.maps.Point(15, 15)
},
visitedMarkerHover: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(120, 0),
anchor: new google.maps.Point(15, 15)
}
I got all icons in one sprite.
I want to set the hover effect for the 'unvisitedMarker' with 'unvisitedMarkerHover' and for 'visitedMarker with 'visitedMarkerHover'. If the marker has the 'activeMarker' icon it should not get a hover effect.
My Problem with this is - i don't know how to set the "if" requirement for that.
//marker hover effect
marker.addListener('mouseover', function() {
if (???) { ... }
});
marker.addListener('mouseout', function() {
if (???) { ... }
});
After that i know i can set the icon with:
marker.setIcon(markerIcon['unvisitedMarker']);
So if someone could help me with the if requirement - that would be awesome!
This one is not that simple. Since I don't have the details such as the URL to your images, I created a sample application in which we have at least 90% similarity. Important: Please don't use the images I've used to avoid copyright issues.
First, I've created public variables: map, markers. "markers" is an empty array.
var map;
var markers = [];
I've also created my own version of markerIcon object.
var markerIcon = {
url : 'http://oi68.tinypic.com/30idv0z.jpg',
unvisitedMarkerHover: 'http://oi65.tinypic.com/jgo3r8.jpg',
originlUrl: 'http://oi68.tinypic.com/30idv0z.jpg',
visitedMarkerHover: 'http://oi65.tinypic.com/ejbn88.jpg',
status: {
unvisitedMarker : {
statusName: 'unvisitedMarker',
},
activeMarker : {
statusName: 'activeMarker',
},
visitedMarker : {
statusName: 'visitedMarker',
}
}
};
I've used a coordinate in San Francisco for my map's center and for Google Maps Javascript API Places Library. I've used Nearby Search as a Place Search and used San Francisco's coordinate for the location property. The radius is set to 500 (measured in meters). This is essential as a combination of the location property - specifying the center of the circle as a LatLng object. For the types, i restricted it only to stores. To learn more about supported types, please check list of supported types.
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatLng,
radius: '500',
type: ['store']
}, callback);
In Nearby Search callback, it returns an array of results. This is what I did:
function createMarker(place, markerId) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
id: markerId,
map: map,
position: placeLoc,
title: 'Hello World!',
anchor: new google.maps.Point(15, 15),
icon: {
url : markerIcon.url,
},
currentStatus: '',
status: markerIcon.status.unvisitedMarker.statusName,
size: new google.maps.Size(30,30),
});
markers.push(marker);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i],i);
}
}
}
I created a createMarker() function that accepts two arguments: the
place object, and markerId.
What the function does is it creates a new Google Maps Javascript
API
Marker
and then set the property and its values accordingly. And also, after
creating the new "marker" object, it will be pushed in to
markers array.
You will also notice that I've added custom properties:
currentStatus, and status. This will play a very important role in
our mouse events.
Since the callback results is an array, I iterate through each array
and called createMarker() function.
This is where the fun begins, in createMarker(), I've also added lines for Google Maps Javascript API Events. This is what I did on my end. Whenever there's a mouseover on a marker, it checks first the currentStatus property of the mouseovered marker. If the currentStatus is an empty string '', it will do another checking for the status property. If the status is 'unvisited', the current icon will now change to a new one. When a mouseout has been detected, the new icon will change to the original one.
Meanwhile, when a marker is clicked, the currentStatus property will be updated to "activeMarker" and then the "status" property is changed to "visitedMarker" as well. You will notice that if the marker has an "activeMarker" currentStatus, nothing will happen when there's a mouseover.
In order to remove the "activeMarker" currentStatus, you will have to click another marker. The "activeMarker" now is transferred to this "another marker". You will also notice that there's a new mouseover effect on the previous marker because I've set a new icon if the marker's status is "unvisitedMarker". You can all find all icon URLs in the markerIcon object.
google.maps.event.addListener(marker, 'mouseover', function() {
if ( this.currentStatus !== markerIcon.status.activeMarker.statusName ) {
if ( this.status === markerIcon.status.unvisitedMarker.statusName ) {
this.setIcon(markerIcon.unvisitedMarkerHover);
} else {
this.setIcon(markerIcon.visitedMarkerHover);
}
this.setPosition(this.position);
console.log(this.currentStatus, this.status, this.id);
}
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.setIcon(markerIcon.originlUrl);
});
google.maps.event.addListener(marker, 'click', function() {
for ( var i = 0; i < markers.length; i++ ) {
markers[i].currentStatus = '';
}
this.currentStatus = markerIcon.status.activeMarker.statusName;
this.status = markerIcon.status.visitedMarker.statusName;
console.log(this.currentStatus, this.status);
});
Whole code below:
var map;
var markers = [];
var markerIcon = {
url : 'http://oi68.tinypic.com/30idv0z.jpg',
unvisitedMarkerHover: 'http://oi65.tinypic.com/jgo3r8.jpg',
originlUrl: 'http://oi68.tinypic.com/30idv0z.jpg',
visitedMarkerHover: 'http://oi65.tinypic.com/ejbn88.jpg',
status: {
unvisitedMarker : {
//origin: new google.maps.Point(0, 0),
statusName: 'unvisitedMarker',
},
activeMarker : {
//origin: new google.maps.Point(60, 0),
statusName: 'activeMarker',
},
visitedMarker : {
//origin: new google.maps.Point(90, 0),
statusName: 'visitedMarker',
},
}
};
function initMap() {
var myLatLng = {lat: 37.773972, lng: -122.431297};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: myLatLng
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatLng,
radius: '500',
type: ['store']
}, callback);
}
function createMarker(place, markerId) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
id: markerId,
map: map,
position: placeLoc,
title: 'Hello World!',
anchor: new google.maps.Point(15, 15),
icon: {
url : markerIcon.url,
},
currentStatus: '',
status: markerIcon.status.unvisitedMarker.statusName,
size: new google.maps.Size(30,30),
});
markers.push(marker);
google.maps.event.addListener(marker, 'mouseover', function() {
if ( this.currentStatus !== markerIcon.status.activeMarker.statusName ) {
if ( this.status === markerIcon.status.unvisitedMarker.statusName ) {
this.setIcon(markerIcon.unvisitedMarkerHover);
} else {
this.setIcon(markerIcon.visitedMarkerHover);
}
this.setPosition(this.position);
//console.log(this.currentStatus, this.status, this.id);
}
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.setIcon(markerIcon.originlUrl);
});
google.maps.event.addListener(marker, 'click', function() {
for ( var i = 0; i < markers.length; i++ ) {
markers[i].currentStatus = '';
}
this.currentStatus = markerIcon.status.activeMarker.statusName;
this.status = markerIcon.status.visitedMarker.statusName;
});
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i],i);
}
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap"
async defer></script>
Hope this application could help and happy coding!

How can I able to display latitude and longitude obtained by json data on google map by using modal for each of the search results in vue js?

I have the following search results coming as the json data. For each search result there is lat and lon. So, for each search result when I click on view map, a modal will pop up and shows the marker on the google map.. but using the following code i am not getting the same..
My json data is
{"status": true, "data": [{"pid": 1, "bussinessName": "ld", "lat": 9.5273308, "lon": 76.8228674, "contactName": "bin"}, {"pid": 2, "bussinessName": "lod", "lat": 9.523308, "lon": 76.8228674, "contactName": "son"},{"pid": 3, "bussinessName": "rd", "lat": 9.5273308, "lon": 76.822867, "contactName": "in"}]}
My vue js code is
<script>
searchContent = new Vue({
el: "#searchContent",
data: {
vector: {}
}
});
categories = new Vue({
el: '#categories',
data: {
articles: [],
services: [],
category: 0,
subcategory: 0,
content: false
},
mounted() {
var vm = this;
$.ajax({
url: "/get_all_category/",
method: "GET",
dataType: "JSON",
success: function(e) {
console.log(e);
vm.articles = e;
console.log(vm);
},
});
},
methods: {
prefetch: function() {
var filter = {};
filter['category'] = this.category;
if (this.content !== false)
this.content.abort()
this.content = $.ajax({
'url': 'https:/filter/',
data: filter,
dataType: "JSON",
type: "POST",
success: function(e) {
window.searchContent.vector = e.data;
console.log(e);
var options = {
zoom: 8,
center: new google.maps.LatLng(e.data.lat , e.data.lon), // Centered
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
// Init map
var map = new google.maps.Map(document.getElementById('mapName'), options);
//use code
var i=0;
// Init markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(e.data.lat , e.data.lon),
map: map,
title: 'Click Me ' + i,
});
// Process multiple info windows
(function(marker, i) {
// add click event
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow({
content: e.data.lat
});
infowindow.open(map, marker);
});
})(marker, i);
}
})
}
}
})
</script>
My html code to display the same is
<div id="searchContent" >
<div v-for="row in vector" >
<h6>{{row.bussinessName}}</h6>
<div>
<a data-toggle="modal" data-target="#myModal1">View Map</a></div>
</div>
</div>
<div id="myModal1" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div id="mapName" style="width:667px; height: 370px" />
<!-- Replace the value of the key parameter with your own API key. -->
</div>
</div>
</div>
So, when I click on the view map I need to display the marker corresponding to the search result. can anyone please help me to solve the problem?
Warning: this isn't a solution - following code only demostrates how easy is to use the ready-made web components. I just think, that this information has it's value and is related to this issue, because it can greatly simplify your code / solution / life :)
Look at this example. It's using extraneous, ready-made Polymer based custom web component from webcomponents.org. As you can see, these components fully interoperates with Vue. You can not only use them, you also have full control about their properties. And best of all, you can listen to their custom events, just like in other Vue components...
So, this is maybe the easiest way to achieve what you need. Just wrap my-map with modal and set the properties to the correct values... And of course, take a look to provided link for documentation for this google-map component.
Vue.component('my-map', {
template: '#my-map',
props: ['lat', 'long'],
data () {
return {
latitude: '',
longitude: ''
}
},
methods: {
setCoords (e) {
if (e.type === 'latitude-changed')
this.latitude = e.detail.value
if (e.type === 'longitude-changed')
this.longitude = e.detail.value
}
}
})
new Vue({
el: '#app'
})
google-map {
height: 186px;
}
<base href="https://raw-dot-custom-elements.appspot.com/GoogleWebComponents/google-map/v2.0.2/google-map/">
<link rel="import" href="google-map.html">
<div id="app">
<my-map lat="37.78" long="-122.4"></my-map>
</div>
<template id="my-map">
<div>
Marker coords: lat {{ latitude }} / long {{ longitude }}
<google-map fit-to-marker api-key="AIzaSyD3E1D9b-Z7ekrT3tbhl_dy8DCXuIuDDRc">
<google-map-marker
:latitude="lat"
:longitude="long"
draggable="true"
slot="markers"
title="Your location"
#latitude-changed="setCoords"
#longitude-changed="setCoords"
>
</google-map-marker>
</google-map>
</div>
</template>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
Honestly ... I think this combination of Vue, and Polymer based custom web components is pretty awesome. Now one can achieve unbelievable results with beautiful, declarative syntax. Did you noticed, that in this example is no additional javascript? Yes, modern browsers works with these custom components with no additional overhead. And for older browsers there is a polyfill...

When clicking cluster, how to show Infowindow which has markers's values?

I have been trying to use google map with angularJS.
I have learned how to use it through https://angular-ui.github.io/angular-google-maps/#!/.
Everything goes well.
For each marker, I can show InfoWindow which has an element information of myList.
But I have got stuck in InfoWindow with cluster.
When cluster is clicked, I want to show the information list of markers in cluster.
Even I can't show simple InforWindow when clicking the cluster.
Below sources are my code.
Please tell me if it is not enough to solve my problem.
Please tell me what is wrong and how to solve this.
Have a nice day.
* javascript
$scope.map.map = {
center: { latitude: $scope.map.myList[0].lat, longitude: $scope.map.myList[0].lng },
zoom: 17,
events : {
tilesloaded: function (map) {
$scope.$apply(function () {
google.maps.event.addDomListener(window, 'resize', function() {
var lat = $scope.map.myList[$scope.map.markerPosition-1].lat;
var lng = $scope.map.myList[$scope.map.markerPosition-1].lng;
var center = new google.maps.LatLng(lat, lng);
map.setCenter(center);
});
});
}
},
markersEvents: {
click: function(marker, eventName, model) {
model.show = !model.show;
return;
}
},
clusterOptions : { // options of cluster
gridSize: 40,
ignoreHidden: true,
zoomOnClick : false,
averageCenter : true,
styles: [
{
height: 53,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png",
width: 53,
textColor : 'white'
}
]
},
clusterEvent: { // when cluster's clicked
click: function(map, markers) {
var contentString = 'ABCD';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, markers);
return;
}
}
};
$scope.map.options = {
streetViewControl : false
};
$scope.map.markers = [];
* html
<ui-gmap-google-map center='map.map.center' zoom="map.map.zoom" options="map.options" events="map.map.events">
<ui-gmap-markers models="map.markers" coords="'self'" icon="a" events="map.map.markersEvents" options="'options'"
doCluster="true" clusterOptions="map.map.clusterOptions" clusterEvents="map.map.clusterEvent">
<ui-gmap-windows show="show">
<div ng-non-bindable>{{id}}</div>
</ui-gmap-windows>
</ui-gmap-markers>
Answer myself.
var infoWindowOptions = {
content: "asdfasdf"
};
var infowindow = new google.maps.InfoWindow(infoWindowOptions);
infowindow.open(map.map_, *marker*);

Categories