how to show multiple markers on google map? - javascript

Here i am making an functionality where i am retrieving the latitude and longitude from JSON file. and showing markers on google map.
But my problem is only one marker is showing on google map. Others is not showing.
here is my json format
{
"Data": {
"-template": "Parallax",
"Explore": {
"IslandLife": {
"TourismLocation": [
{
"Title": "Langkawi",
"Latitude": "6.350000",
"Longitude": "99.800000",
"YouTubePlaylistID": "UUnTJRksbHP4O8JSz00_XRQA",
"VideosList": {
"YouTubeVideoID": [
"7HlMpaSspNs",
"tzeRnbd77HU",
"VkIAbDIVJCA",
"ksJ6kwTe9wM"
]
}
},
{
"Title": "Rawa Island",
"Latitude": "2.520278",
"Longitude": "103.975833",
"YouTubePlaylistID": "UUnTJRksbHP4O8JSz00_XRQA",
"VideosList": { "YouTubeVideoID": "Kx0dUWaALKo" }
},
{
"Title": "Perhentian Island",
"Latitude": "5.903788",
"Longitude": "102.753737",
"YouTubePlaylistID": "UUnTJRksbHP4O8JSz00_XRQA",
"VideosList": {
"YouTubeVideoID": [
"ZpcdGk5Ee0w",
"TQTDOGpflZY"
]
}
},
{
"Title": "Sabah Marine Park",
"Latitude": "4.623326",
"Longitude": "118.719800",
"YouTubePlaylistID": "UUnTJRksbHP4O8JSz00_XRQA",
"VideosList": { "YouTubeVideoID": "VCDTEKOqpKg" }
}
]
}
}
}
}
here my function where i am retriving latitude and lognitutde from above json file
<script type="text/javascript">
$.getJSON('json/explore.json', function(data) {
$.each(data, function(key, val) {
for (var i = 0; i < val.Explore.IslandLife.TourismLocation.length; i++) {
PlotMarker(val.Explore.IslandLife.TourismLocation[i].Latitude, val.Explore.IslandLife.TourismLocation[i].Longitude);
}
});
});
function PlotMarker(lat, lang) {
var mapProp = {
center: new google.maps.LatLng(lat, lang),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"), mapProp);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lang),
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', PlotMarker);
</script>
<body>
<div id="gmap" style="width: 800px; height:500px;"></div>
</body>
How to show multiple markers on map ???

Your issue here is scope - you are recreating the map every time you call PlotMarker - so each time it has only one marker added to it. Declare your map outside of the PlotMarker function, something like:
initialize() {
var mapProp = {
center: new google.maps.LatLng(lat, lang),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"), mapProp);
}
function PlotMarker(lat, lang) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lang),
});
marker.setMap(map);
}
And then call initialize() on page load - also, ensure the map exists before calling the PlotMarker function.
Another good SO answer with some sample code: https://stackoverflow.com/a/7701386/1803682

The below is a working sample that I use in my project
JS method AddInfoWidnow used to add InfoWindow to a marker.
function AddInfoWidnow(marker,message)
{
var infowindow = new google.maps.InfoWindow({ content: message });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(marker.get('map'), marker);
});
}
call the AddInfoWidnow method inside the for loop
function ShowOnMap(ContainerId, mapItems) {
var DefaultLatLng= new google.maps.LatLng('12.967461', '79.941824');
var mapOptions = {
center: DefaultLatLng,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
marker: true
};
var mapCust = new google.maps.Map(document.getElementById(ContainerId), mapOptions);
var arrJsonObject = JSON.parse(mapItems);
for (var y = 1; y <= arrJsonObject.length; y++)
{
var myLatLng1 = new google.maps.LatLng(arrJsonObject[y - 1].Latitude, arrJsonObject[y - 1].Lonngitude);
var marker = new google.maps.Marker({
position: myLatLng1,
map: mapCust,
title: 'Marked at '+ arrJsonObject[y - 1].markedDate
});
addInfoWindows(marker,y-1,arrJsonObject);
marker.setMap(mapCust);
}
}
Use the below snnipet to call the map
var mapItems='[
{
"Latitude": "22.575897",
"Lonngitude": "88.431754",
"CustomerCode": "*$$$*",
"CustomerName": "*###*",
"markedDate": "2/20/2014 12:04:41 PM"
},
{
"Latitude": "22.615067",
"Lonngitude": "88.431759",
"CustomerCode": "*$$$*",
"CustomerName": "*###*",
"markedDate": "2/20/2014 3:02:19 PM"
}
]';
ShowOnMap(containerId2, mapItems);

Related

Google Maps Infowindow issue after Geocode adaptation

I switched my code from the lat-lang system to the geocode API in order to resolve addresses, but unfortunately, the Google Maps Infowindows don't work properly. Only a few of them are displayed, with wrong information.
Here there is my code.
<script type="text/javascript">
if(document.getElementById("{idMap}")) {
let geocoder;
let map;
let locations = [
[ "Location 1" , "Via Pavia 57, 80021" ] ,
[ "Location 2" , "Via Palermo 24, 80021" ] ,
[ "Location 3" , "Via Milano 15, 80021" ] ,
];
function initializeMap() {
geocoder = new google.maps.Geocoder();
let infowindow = new google.maps.InfoWindow();
let bounds = new google.maps.LatLngBounds();
let mapSettings = {
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
};
map = new google.maps.Map(document.getElementById("{idMap}"), mapSettings);
for (i = 0; i < locations.length; i++) {
codeAddress(locations[i][1], i, bounds);
}
}
function codeAddress(address, index, bounds) {
geocoder.geocode({ address: address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
let latLng = {
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng(),
};
if (status == "OK") {
let marker = new google.maps.Marker({
position: latLng,
map: map,
icon: "https://maps.google.com/mapfiles/ms/icons/blue-dot.png",
});
bounds.extend(marker.position);
map.fitBounds(bounds);
map.panToBounds(bounds);
if(locations[0][index] && locations[0][index].length > 0) {
let infowindow = new google.maps.InfoWindow({
content: locations[0][index],
});
marker.addListener("click", function () {
infowindow.open(map, marker);
});
}
} else {
console.log(
"Geocode was not successful for the following reason: " + status
);
}
}
});
}
window.initMap = null;
window.initMap = initializeMap();
}
</script>
All the markers are correctly positioned, the issue is only related to the infoWindow.
I fixed the issue, passing the id from the marker to the location array, in this way it works:
let infowindow = new google.maps.InfoWindow({
content: locations[marker.id][1],
});

javascript of HTML content within a Google Map info window is not executed

I've got the following JSON file:
{
"places" : [
{
"place": "A",
"place_id": "ChIJIQs8RmOQdkcRkR07PeyDqhw",
"lat": 47.803488,
"lng": 13.045824
},
{
"place": "B",
"place_id": "ChIJY60NGmOQdkcRnHyLQNKMWOg",
"lat": 47.802524,
"lng": 13.046177
},
{
"place": "​C",
"place_id": "ChIJKR11Md-QdkcRIcl4Mu8D0DA",
"lat": 47.773108,
"lng": 13.069841
}
]
}
Based on this data, I'm creating 3 markers.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(47.5,13.2)
});
var infowindow = new google.maps.InfoWindow();
var json = "http://127.0.0.1/json/data.json";
$.getJSON(json, function(json1) {
$.each(json1.places, function (key, data) {
var latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.place
});
bindInfoWindow(marker, map, infowindow, data.place_id);
});
});
}
function bindInfoWindow(marker, map, infowindow, myPlace) {
google.maps.event.addListener(marker, 'click', function () {
$.ajax({
url: 'infowindowcontent.html?place_id=' + myPlace,
dataType: 'html',
success: function(data) {
infowindow.setContent(data);
infowindow.open(map, marker);
}
});
});
}
The called infowindowcontent.html code looks like this:
<div>
<div id="dynamiccontent">no no no</div>
</div>
<script>
document.getElementById("dynamiccontent").innerHTML = "hey hey hey"
</script>
Each code is working fine on its own.
But the infowindowcontent.html code is called by clicking a marker. The info windows is displayed, but the javascript isn't executed. I still read 'no no no' instead of 'hey hey hey'. Any suggestions? Thanks.

Google Maps JavaScript API markers & infowindows

I'm facing an issue with the open method on infoWindow object.
I want to set all my map utility objects dynamically but when the open method is called it raises me an error because the infoWindow object associated is undefined.
Here is my code :
// Markers & infoWindows
var markers = [];
var infoWindows = [];
for(var i=0; i<myList.length; i++) {
markers.push(
new google.maps.Marker({
position: myList[i].coord,
map: map,
title: myList[i].city
})
);
infoWindows.push(
new google.maps.InfoWindow({
content: myList[i].address
})
);
markers[i].addListener('click', function() {
infoWindows[i].open(map, markers[i]);
});
}
[ Where myList is just an arry of JSON formated objects. ]
All the markers and infoWindows are well set. I can access their properties and print them to the console.
But as I said the infoWindows[i] is typed undefined so the open method isn't found. A contrario I can access and print the content attribute of this infoWindows[i] object. Seems weird to me...
If someone is able to explain me I will be happy :)
Related question: Google Maps JS API v3 - Simple Multiple Marker Example
When the loop completes i is left at infoWindows.length, which is past the end of the array. One way to fix it is with function closure on i:
markers[i].addListener('click', (function(i) {
return function() {
infoWindows[i].open(map, markers[i]);
}}(i)));
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
// Markers & infoWindows
var markers = [];
var infoWindows = [];
for (var i = 0; i < myList.length; i++) {
markers.push(
new google.maps.Marker({
position: myList[i].coord,
map: map,
title: myList[i].city
})
);
infoWindows.push(
new google.maps.InfoWindow({
content: myList[i].address
})
);
markers[i].addListener('click', (function(i) {
return function() {
infoWindows[i].open(map, markers[i]);
}
}(i)));
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
var myList = [{
coord: {
lat: 42,
lng: -72
},
city: "Somewhere",
address: "Somewhere"
}, {
coord: {
lat: 40.7127837,
lng: -74.0059413
},
city: "New York, NY, USA",
address: "New York, NY, USA"
}, {
coord: {
lat: 40.735657,
lng: -74.1723667
},
city: "Newark, NJ, USA",
address: "Newark, NJ, USA"
}];
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Trying to parse external json file to create markers in google maps api

I am using JavaScript and a external JSON file.
Here is my JSON file. It is in the same folder as my js file. I called the JSON file csus_locations.JSON
{
"locations": [
{
"latitude": 38.558961,
"longitude": -121.423011,
"name": "AIRC",
"title": "THIS IS WHERE STUFF GETS DONE!"
},
{
"latitude": 38.562605,
"longitude": -121.419683,
"name": "GUY WEST",
"title": "PRESIDENT?"
},
{
"latitude": 38.556652,
"longitude": -121.423842,
"name": "well",
"title": "WORKOUT"
},
{
"latitude": 38.555465,
"longitude": -121.422551,
"name": "Hornetsatdium",
"title": "FOOTBAL!"
}
]}
I Know that this is legal json code because i tested to verify it. But can i remove "locations": and remove the brackets to make it simpler to parse into google maps?
I am trying to parse the json file using $http.get but my i am note sure if i wrote the code correctly
angular.module('app.controllers', ['ionic'])
.controller('mapCtrl', function ($scope, $ionicSideMenuDelegate, $ionicLoading, $compile, $ionicPopup, $http) {
$ionicSideMenuDelegate.canDragContent(false);
var myLatlng = new google.maps.LatLng(38.5602, -121.4241);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Sac State'
});
//i want to get parse with $http.get but i am not sure if i wrote this code correctly
$http.get('csus_locations.json').success(function(res){
console.log("success!");
$scope.locations = res.locations;
//window.alert("The app is reading the Json file!"); this was a test to see if the get function was working
var latLng_csus = new google.maps.LatLng(value.latitude, value.longitude);
var marker = new google.maps.Marker({
position: latLng_csus,
title: value.name
});
});
/* this was my first attempt to create markers
console.log(jsonCSUS);
angular.forEach(jsonCSUS, function(value, key){
var latLng_csus = new google.maps.LatLng(value.latitude, value.longitude);
var marker = new google.maps.Marker({
position: latLng_csus,
title: value.name
});
marker.setMap(map);
});*/
var onSuccess = function (position) {
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
$scope.map = map;
//$scope.map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.watchPosition(onSuccess, onError, {
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true
});
});
The provided JSON file, indeed is a valid one, so you could initialize markers like this:
$http.get('csus_locations.json').success(function (data) {
$scope.locations = data.locations;
$scope.locations.forEach(function(item){
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker({
position: latLng,
title: item.name,
map: map
});
});
});
Working example
angular.module('mapApp', ['ionic'])
.controller('mapCtrl', function ($scope, $http) {
var mapOptions = {
center: new google.maps.LatLng(38.5602, -121.4241),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
$http.get('https://gist.githubusercontent.com/vgrem/c7ec78e7078c2c9ed1c3/raw/959e9d8b8e60544fcc169ea890e84a2624ed8bbb/csus_locations.json').success(function (data) {
$scope.locations = data.locations;
$scope.locations.forEach(function(item){
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker({
position: latLng,
title: item.name,
map: map
});
});
});
});
#map-canvas {
width: 800px;
height: 600px;
}
<link href="http://code.ionicframework.com/1.1.1/css/ionic.css" rel="stylesheet">
<script src="http://code.ionicframework.com/1.1.1/js/ionic.bundle.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true"></script>
<div ng-app="mapApp" ng-controller="mapCtrl">
<div id="map-canvas"></div>
</div>

How to show 2 markers on a Google Map?

How do I get multiple markers on a Google Map, using Javascript API v3? Below, when my code adds the second marker it's removing the first one.
var locations = {
"1" : {
"name": "location1",
"address": "10000 N Scottsdale Rd",
"city": "Scottsdale",
"state": "AZ",
"zipcode": "85253"
},
"2" : {
"name": "location2",
"address": "15440 N 71st Street",
"city": "Scottsdale",
"state": "AZ",
"zipcode": "85254"
}
}
var geocoder = new google.maps.Geocoder();
for (item in locations) {
var loc = locations[item].address + ", " + locations[item].city + " " +
locations[item].state + " " + locations[item].zipcode;
geocoder.geocode( { 'address': loc}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var options = {
zoom: 10,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
}
if (map) {
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: locations[item].name
});
} else {
var map = new google.maps.Map(document.getElementById("map"), options);
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: locations[item].name
});
}
var infowindow = new google.maps.InfoWindow({ content: "test"});
} else { // if map lookup fails, display a map of phoenix
var phoenix = new google.maps.LatLng(33.4483771,-112.07403729999999);
var options = {
zoom: 11,
center: phoenix,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
}
map = new google.maps.Map(document.getElementById("map"), options);
}
});
}
The map variable is only defined in the callback function, (e.g. function(results, status) {...}), so when the second geocoded point comes back, you are still creating a new map (for the second time), since that map is not initialized.
You should declare and initialize the map separately from the marker adding code.
loop through your marker construction from your data set. Each item in your set, create a marker as you normally would. instatiate your map only once and use the variable assigned to this in your marker creation.

Categories

Resources