Google Maps API - Show multiple marker tool tips - google-maps

I have a map with markers on it, but I want to be able to show multiple tool tips.
It seems when I do:
marker.openInfoWindowHtml(strToolTip);
...each time it is called, it closes the previous tool tip.
Any ideas how I show multiple marker tool tips on the same map?
Thanks

Have you tried creating a new infowindow object on marker click event and opening it?
var infowindow = new google.maps.InfoWindow({ content: 'Hello world' });
infowindow.open(map, marker);

You can try this:
var markers = [
{ lat: 28.7051, lng: 77.1125 },
{ lat: 28.7081, lng: 77.1075 },
{ lat: 28.7021, lng: 77.1315 }
]
var index=0;
markers.forEach(function (marker) {
var self=this;
(function (marker) {
let mark = new google.maps.Marker({ position: new google.maps.LatLng(marker.lat, marker.lng) });
var infowindow = new google.maps.InfoWindow({ content: index });
infowindow.open(self.map, marker);
mark.setMap(self.map);
index++;
})(marker)
})
Note: The sequence of open() & setMap() must be like above/below code.
Ex:
infowindow.open(self.map, marker);
mark.setMap(self.map);
Snapshot are below:
If you are using angular2/4/5 then have a look on the complete code:
map.component.ts:
import { Component, ViewChild } from '#angular/core';
import { } from '#types/googlemaps'; // You need to install #types/googlemaps, To know how hit this URL- https://medium.com/#svsh227/integrate-google-api-map-in-your-angular-2-4-5-app-472bf08fdac
#Component({
selector: 'map-component',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent {
#ViewChild('map') gmapElement: any;
map: google.maps.Map;
ngOnInit() {
var markers = [
{ lat: 28.4685, lng: 77.0056, toolTip: 'Here too' },
{ lat: 28.4795, lng: 77.0276, toolTip: 'Here too' },
{ lat: 28.4605, lng: 77.0546, toolTip: 'Here too' }
]
// For center
var mapProp = {
center: new google.maps.LatLng(28.4595, 77.0266),
zoom: 13,
mapTypeId: google.maps.MapTypeId.HYBRID // also use ROADMAP,SATELLITE or TERRAIN
};
this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
var marker = new google.maps.Marker({ position: mapProp.center });
marker.setMap(this.map);
var infowindow = new google.maps.InfoWindow({ content: "Hey !! Here we are" });
infowindow.open(this.map, marker);
this.setMultipleMarker(markers, this);
}
setMultipleMarker(markers, self) {
markers.forEach(function (marker) {
(function (marker) {
let mark = new google.maps.Marker({ position: new google.maps.LatLng(marker.lat, marker.lng) });
let infowindow = new google.maps.InfoWindow({ content: marker.toolTip });
infowindow.open(self.map, mark);
mark.setMap(self.map);
})(marker)
})
}
}
map.component.html:
<div>
<br />
<h1>
<span class="heading-text">Here We Are</span>
</h1>
<div class="row" class="card-details rcorners3 card-height">
<div class="card" class="subAbout tech-stack">
<div class="card-header card-header-us">
<div id="map" #map></div>
</div>
</div>
</div>
</div>
And here is the output/Snapshot:

Related

Dynamic marker and infoWindow Google Maps API using Google App Engine parsing through a JSON file

Hi I'm new to stackoverflow (and coding) but I am working on a web-application where I want to add dynamic markers and infowindows based on an extracted JSON file. There are over 200 markers, so they need to be dynamic. I have code that works to add markers but as soon as I add infoWindows it doesn't. Can anybody see why? The output dropped to just one marker and no infoWindow.
Here is my code:
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
infowindow = new google.maps.InfoWindow();
for (element in data) {
new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
infowindow.setContent(data[element].country);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
}
});
}
I saw a post on stackoverflow with a similar question and tried it that way as well but didnt get any markers.
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
var json = data = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].lat, json[i].lon);
contentString = json[i].Country;
addMarkers(point, contentString);
}
}
});
function addMarkers(point, contentString) {
marker = new google.maps.Marker({
position: point,
map: map
});
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.push(marker);
infos.push(infowindow);
for (var j = 0; j < markers.length; j++) {
google.maps.event.addListener(markers[j], 'click', function() {
infos[j].open(map, markers[j]);
})
}
}
}
The output of my JSON file looks like this:
{
"AA": {
"celsius": 32.27777777777778,
"country": "AA",
"day": "25",
"lat": 12.5,
"lon": -70.017,
"month": "03"
},
...
}
There are a few issues in your code. You should read Using Closures in Event Listeners.
You should set the infowindow content on marker click (not within the loop, as you did)
You should declare the marker variable which is missing
Any variable you are using must be declared, for example for (element in data) should be for (var element in data)
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
console.log(data);
infowindow = new google.maps.InfoWindow();
for (var element in data) {
var marker = new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
google.maps.event.addListener(marker, 'click', (function(marker, element) {
return function() {
var content = 'Country: ' + data[element].country;
content += '<br>Temperature (°C): ' + data[element].celsius;
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, element));
}
}
});
}
initMap();
#map {
height: 180px;
}
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

IONIC 3 google map is ready but nothing showing in the map

I am new on ionic and integrating google map one of my app. I have everything installing google map plugin using apikey and writing some code here it is:
#ViewChild('map') mapElement: ElementRef;
map: GoogleMap;
spaArray:any = []
setupLocation(){
this.location = new LatLng(42.346903, -71.135101);
//Add cluster locations
this.locations.push({position: {lat: 42.346903, lng: -71.135101}});
this.locations.push({position: {lat: 42.342525, lng: -71.145943}});
this.locations.push({position: {lat: 42.345792, lng: -71.138167}});
this.locations.push({position: {lat: 42.320684, lng: -71.182951}});
this.locations.push({position: {lat: 42.359076, lng: -71.0645484}});
this.locations.push({position: {lat: 42.36, lng: -71.1}});
}
ionViewDidLoad() {
this.provider.presentLoadingDefault()
this.platform.ready().then(() => {
// let element = this.mapElement.nativeElement;
let element: HTMLElement = document.getElementById(this.mapElement.nativeElement);
this.map = this.googleMaps.create(this.mapElement.nativeElement);
// this.map.clear();
this.map.one(GoogleMapsEvent.MAP_READY).then(() => {
this.provider.hideLoader()
let options = {
target: this.location,
zoom: 8
};
this.map.moveCamera(options);
setTimeout(() => {this.addCluster()}, 500);
});
});
}
html is here
<ion-content>
<div #map style="height: 100%" id="map"></div>
</ion-content>
but when I am running the app into my mobile its only showing blank map with google logo bottom of this.
Help me into this please.
Here you have a working example:
import {
GoogleMaps,
GoogleMap,
GoogleMapsEvent,
GoogleMapOptions,
CameraPosition,
MarkerOptions,
Marker,
MarkerCluster,
LatLng,
HtmlInfoWindow,
MyLocation
} from '#ionic-native/google-maps';
inside your class:
private mapElement: HTMLElement;
private map: GoogleMap;
inside your platform.ready().then()
this.mapElement = document.getElementById('map');
// DEFINE YOUR OWN MAP SETTINGS
let mapOptions: GoogleMapOptions = {
controls: {
indoorPicker: true
},
gestures: {
rotate: true,
scroll: true,
tilt: true,
zoom: true
},
preferences: {
building: true,
zoom: {
maxZoom: 20,
minZoom: 1
}
}
};
this.map = GoogleMaps.create(this.mapElement, mapOptions);
// Wait the MAP_READY before using any methods.
this.map.one(GoogleMapsEvent.MAP_READY)
.then(() => {
// DO MAP STUFF HERE
});
this should work fine.

SetPosition: not a LatLng or LatLngLiteral: in property lat: not a number using React and Google Maps

I am trying to display multiple markers using google maps and react but keep getting the error mentioned above. The idea is to have multiple markers displayed from lat and long cords in an array. Any thoughts?
Codepen: http://codepen.io/anon/pen/evOoNP?editors=0010
class GMap extends React.Component {
state = { zoom: 10 };
static propTypes() {
initialCenter: React.PropTypes.objectOf(React.PropTypes.number).isRequired
}
render() {
return <div className="GMap">
<div className='UpdatedText'>
<p>Current Zoom: { this.state.zoom }</p>
</div>
<div className='GMap-canvas' ref="mapCanvas">
</div>
</div>
}
componentDidMount() {
// create the map, marker and infoWindow after the component has
// been rendered because we need to manipulate the DOM for Google =(
this.map = this.createMap()
this.marker = this.createMarker()
this.infoWindow = this.createInfoWindow()
// have to define google maps event listeners here too
// because we can't add listeners on the map until its created
google.maps.event.addListener(this.map, 'zoom_changed', ()=> this.handleZoomChange())
}
// clean up event listeners when component unmounts
componentDidUnMount() {
google.maps.event.clearListeners(map, 'zoom_changed')
}
createMap() {
let mapOptions = {
zoom: this.state.zoom,
center: new google.maps.LatLng(38, -78)
}
return new google.maps.Map(this.refs.mapCanvas, mapOptions)
}
mapCenters() {
return new google.maps.LatLng(
this.props.initialCenter.lat,
this.props.initialCenter.lng
)
}
mapCenter() {
const navLinks = [
{location: "Bondi Beach", lat: -33.890542, long: 151.274856},
{location: "Coogee Beach", lat: -33.923036, long: 151.259052},
{location: "Cronulla Beach", lat: -34.028249, long: 151.157507}
];
return navLinks.map((b, i) => {
console.log(b)
return new google.maps.LatLng(b.lat, b.long)
})
}
createMarker() {
return new google.maps.Marker({
position: this.mapCenter(),
map: this.map
})
}
createInfoWindow() {
let contentString = "<div class='InfoWindow'>I'm a Window that contains Info Yay</div>"
return new google.maps.InfoWindow({
map: this.map,
anchor: this.marker,
content: contentString
})
}
handleZoomChange() {
this.setState({
zoom: this.map.getZoom()
})
}
}
var initialCenter = { lng: -90.1056957, lat: 29.9717272 }
ReactDOM.render(<GMap initialCenter={initialCenter} />, document.getElementById('container'));
new google.maps.Marker({
position: this.mapCenter(), // here is the problem
map: this.map
})
Your mapCenter() method returns an array of coordinates, but new google.maps.Marker({}) expects a single LatLng to be passed as position.
You need to update your createMarker() method to create the markers in a loop, for example:
createMarker() {
return this.mapCenter().map( point => {
return new google.maps.Marker({
position: point,
map: this.map
})
});
}
http://codepen.io/anon/pen/yMLYBa?editors=0010

Display Multiple Markers with Google Maps and React Js ES6

I am able to display one marker but when I map create new google.maps.Marker inside my loop nothing is returned. Has anyone encoutnered this before? Code Below and codepen attached.
Codepen: http://codepen.io/anon/pen/pezqKq?editors=0010
class GMap extends React.Component {
state = { zoom: 10 };
static propTypes() {
initialCenter: React.PropTypes.objectOf(React.PropTypes.number).isRequired
}
render() {
return <div className="GMap">
<div className='UpdatedText'>
<p>Current Zoom: { this.state.zoom }</p>
</div>
<div className='GMap-canvas' ref="mapCanvas">
</div>
</div>
}
componentDidMount() {
// create the map, marker and infoWindow after the component has
// been rendered because we need to manipulate the DOM for Google =(
this.map = this.createMap()
this.marker = this.createMarker()
this.infoWindow = this.createInfoWindow()
// have to define google maps event listeners here too
// because we can't add listeners on the map until its created
google.maps.event.addListener(this.map, 'zoom_changed', ()=> this.handleZoomChange())
}
// clean up event listeners when component unmounts
componentDidUnMount() {
google.maps.event.clearListeners(map, 'zoom_changed')
}
createMap() {
let mapOptions = {
zoom: this.state.zoom,
center: this.mapCenter()
}
return new google.maps.Map(this.refs.mapCanvas, mapOptions)
}
mapCenter() {
return new google.maps.LatLng(
this.props.initialCenter.lat,
this.props.initialCenter.lng
)
}
createMarker() {
const navLinks = [
{location: 'Bondi Beach', lat: -33.890542, long: 151.274856},
{location: 'Coogee Beach', lat: -33.923036, long: 151.259052},
{location: 'Cronulla Beach', lat: -34.028249, long: 151.157507},
{location: 'Manly Beach', lat: -33.80010128657071, long: 151.28747820854187}
];
navLinks.map((b, i) => {
return new google.maps.Marker({
position: new google.maps.LatLng(b.lat, b.long),
map: this.map
})
console.log(b.long)
})
}
createInfoWindow() {
let contentString = "<div class='InfoWindow'>I'm a Window that contains Info Yay</div>"
return new google.maps.InfoWindow({
map: this.map,
anchor: this.marker,
content: contentString
})
}
handleZoomChange() {
this.setState({
zoom: this.map.getZoom()
})
}
}
var initialCenter = { lng: -90.1056957, lat: 29.9717272 }
ReactDOM.render(<GMap initialCenter={initialCenter} />, document.getElementById('container'));
In createMarker you aren't actually returning anything. You need to return the navLinks.map. You also aren't seeing that console.log because you have it below the return statement in the map.
return navLinks.map((b, i) => {
console.log(b.long)
return new google.maps.Marker({
position: new google.maps.LatLng(b.lat, b.long),
map: this.map
})
})

AngularJs- TypeError: Cannot read property 'latitude' of undefined

I want to show Google map with draggable marker in my page . Here is my code:
header.php :
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true"></script>
map.js:
app.directive('mapDirective',function(){
return {
templateUrl: 'map.html',
restrict: 'EA',
require: '?ngModel',
scope:{
myModel: '=ngModel'
},
link: function(scope , element, attrs , ngModel){
var mapOptions;
var googleMap;
var searchMarker;
var searchLatLng;
scope.searchLocation = {
latitude: 48.137273,
longitude: 11.575251
};
ngModel.$render = function(){
console.log("hhh");
searchLatLng = new google.maps.LatLng(scope.myModel.latitude, scope.myModel.longitude);
mapOptions = {
center: searchLatLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
googleMap = new google.maps.Map(element[0],mapOptions);
searchMarker = new google.maps.Marker({
position: searchLatLng,
map: googleMap,
draggable: true
});
google.maps.event.addListener(searchMarker, 'dragend', function(){
scope.$apply(function(){
scope.myModel.latitude = searchMarker.getPosition().lat();
scope.myModel.longitude = searchMarker.getPosition().lng();
});
}.bind(this));
};
scope.$watch('myModel', function(value){
var myPosition = new google.maps.LatLng(scope.myModel.latitude, scope.myModel.longitude);
searchMarker.setPosition(myPosition);
}, true);
}
}
});
map.html:
<div>
<div style="display: block; height: 200px; width: 100%; ">
</div>
</div>
index.html:
<map-directive ng-model="testModel"></map-directive>
Actually , I got this error :
TypeError: Cannot read property 'latitude' of undefined
How to solve it?
EDITED:
I change my maps.js:
app.directive('mapDirective',function(){
return {
templateUrl: '/app/user/ngApp/templates/libsView/templates/directives/map.html',
restrict: 'EA',
require: '?ngModel',
scope:{
myModel: '=ngModel'
},
controller: function ($scope) {
$scope.searchLocation = {
latitude: 48.137273,
longitude: 11.575251
};
},
link: function(scope , element, attrs , ngModel){
var mapOptions;
var googleMap;
var searchMarker;
var searchLatLng;
ngModel.$render = function(){
console.log("hhh");
searchLatLng = new google.maps.LatLng(scope.myModel.latitude, scope.myModel.longitude);
mapOptions = {
center: searchLatLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
googleMap = new google.maps.Map(element[0],mapOptions);
searchMarker = new google.maps.Marker({
position: searchLatLng,
map: googleMap,
draggable: true
});
google.maps.event.addListener(searchMarker, 'dragend', function(){
scope.$apply(function(){
scope.myModel.latitude = searchMarker.getPosition().lat();
scope.myModel.longitude = searchMarker.getPosition().lng();
});
}.bind(this));
};
scope.$watch('myModel', function(value){
var myPosition = new google.maps.LatLng(scope.myModel.latitude, scope.myModel.longitude);
searchMarker.setPosition(myPosition);
}, true);
}
}
});
But it doesn't change.
myModel variable should contains latitude and longitude values. which should be set from
<map-directive ng-model="testModel"></map-directive>
You need to create a object as below in your controller and assign this object to directive as above html.
var testModel = {
latitude:1.2323,
longitude:2.3434
};