How to show 2 markers on a Google Map? - javascript

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.

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],
});

google map is rendered with multiple rounded tiles

map is devided into 3x3 tiles
I want to remove all the spaces and rounded corners so the map looks as if it is one full map without any divisions into tiles, maybe there is some kind of map tile atribute that I can modify to make it look like a normal map, below is my code
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
});
google.maps.event.trigger(map, 'resize');
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
swal("не удалось загрузить карту");
}
});
}
initMap();
the tiles of the map are effected by img styling, I changed my css to bypass the map styling and it solved my issue

Google Maps API: Geocoder: unknown property function:

I'm currently trying to Google Geocoder API to convert an address into Lat/Lng coordinates, however, when using the example on their dev documentation(https://developers.google.com/maps/documentation/javascript/geocoding), I am running into an error of "InvalidValueError: unknown property function"
In my HTML file, I have the call to google map API and a map div, where my map should be rendered. (of course i have other stuff too, but just for the sake of getting straight to the point i will only post the relevant code)
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap" async defer></script>
<div id="map"></div>
And in my JS file:
window.initMap = function(){
var fromLocation = new google.maps.LatLng(37.09024, -95.712891),
destLocation = new google.maps.LatLng(37.09024, -95.712891),
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.09024 , lng: -95.712891}, // center of USA
zoom: 4 // continet level
}),
directionService = new google.maps.DirectionsService(),
directionRender = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "From",
map:map
}),
markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label:"Destination",
map:map
});
getLatLng("Los Angeles");
} // end of initMap
function getLatLng(address){
geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address, function(results,status){
if(status === 'OK'){
console.log(results[0].geometry.location);
}
else{
console.log("Geocoding couldn't convert string address to lat/long points");
}
}
});// end of geocoder method.
}
Any idea on how to fix the unknown property function error?
Thanks!
You have a typo in the function getLatLng:
geocoder.geocode({
address: address,
There needs to be a "}" after address: address
function getLatLng(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: address},
function(results, status) {
if (status === 'OK') {
console.log(results[0].geometry.location);
} else {
console.log("Geocoding couldn't convert string address to lat/long points");
}
}); // end of geocoder method.
}
window.initMap = function() {
var fromLocation = new google.maps.LatLng(37.09024, -95.712891),
destLocation = new google.maps.LatLng(37.09024, -95.712891),
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 37.09024,
lng: -95.712891
}, // center of USA
zoom: 4 // continet level
}),
directionService = new google.maps.DirectionsService(),
directionRender = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "From",
map: map
}),
markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label: "Destination",
map: map
});
getLatLng("Los Angeles");
} // end of initMap
function getLatLng(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: address
},
function(results, status) {
if (status === 'OK') {
console.log(results[0].geometry.location);
} else {
console.log("Geocoding couldn't convert string address to lat/long points");
}
}); // end of geocoder method.
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<div id="map"></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 multiple markers on google map?

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);

Categories

Resources