Angularjs and Google maps marker cluster - javascript

I'm new with Google Maps and I add ng-map but I have the same problem of official plunker code plunker, markers don't appear.
This is my Angularjs code:
//Google maps
var app = angular.module('myApp',['ngMap', 'ngAnimate', 'ui.bootstrap', 'ui.select']);
app.controller('mapController', ['$scope','$http', 'NgMap', function($scope, $http, NgMap) {
NgMap.getMap().then(function(map) {
//Get all buildings for maps
$http({
method: 'GET',
url: '/booking/building/1',
}).then(function successCallback(response) {
if (typeof response.data.success == 'undefined'){
window.location.href = "/500";
}else if (response.data.success==true){
for (var i=0; i < response.data.result.length;i++){
var latLng = new google.maps.LatLng(response.data.result[i].latitude, response.data.result[i].longitude);
vm.dynMarkers.push(new google.maps.Marker({position:latLng, title:response.data.result[i].name}));
}
}else if (response.data.success==false)
notifyMessage(response.data.result, 'error');
}, function errorCallback(response) {
window.location.href = "/500";
});
vm.markerClusterer = new MarkerClusterer(map, vm.dynMarkers, {});
});
});
In this case I have only 1 city, but in the future I may have a loto of coordinates.
In Html I have this script about ng-map:
<!-- Maps -->
<script th:src="#{/static/assets/plugins/angular-maps/ng-map.min.js}"
type="text/javascript"></script>
<script
src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/testapp/scripts/markerclusterer.js"></script>
<script>
MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_
= 'https://raw.githubusercontent.com/googlemaps/js-marker-clusterer/gh-pages/images/m1.png'; //changed image path
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=key">
</script>
I tryed to remove
<script>MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH = 'https://raw.githubusercontent.com/googlemaps/js-marker-clusterer/gh-pages/images/m1.png'; //changed image path
</script>
but the result still the same. I would like to uso only maps CDN link.

I found out that vm.markerClusterer = new MarkerClusterer(map, vm.dynMarkers, {}); is called before for inside ajax is terminated so the vatiable is empty so I moved it after the end of for and it works
for (var i=0; i < response.data.result.length;i++){
var latLng = new google.maps.LatLng(response.data.result[i].latitude, response.data.result[i].longitude);
vm.dynMarkers.push(new google.maps.Marker({position:latLng, title:response.data.result[i].name}));
}
vm.markerClusterer = new MarkerClusterer(map, vm.dynMarkers, {});

Related

google api key as a variable

<script src="jquery.js"></script>
<script>
$.get('http://localhost/ajax_send_key.php',function (data){
api_key = data;
});
</script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key= - my api key - &libraries=places">
// this one work
// src="https://maps.googleapis.com/maps/api/js?key={api_key}&libraries=places">
// Google Maps JavaScript API error: InvalidKeyMapError
// src="https://maps.googleapis.com/maps/api/js?key=" + api_key + "&libraries=places">
// TypeError: Cannot read properties of undefined (reading 'Autocomplete') at initialize
</script>
<script>
lat = '';
function initialize() { // google places wohl für ortseingabe und dann vorschläge
var input = document.getElementById('in');
var places = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var lat = place.geometry.location.lat();
});
return (lat);
}
window.addEventListener('load', initialize);
</script>
<html>
input
<input id='in' type = 'text' STYLE = 'width: 220px' ;></input>
</html>
hello,
I have a problem with my Api Key, when I try to use it as a variable. how do I put it into the src="https://maps.googleapis.com/maps/api/js?key=
It works if it is not a variable.
thanks georg
Don't create the script tag on load. Wait for the key response to come back first before creating it, and then you can create the src appropriately. You'll also have to wait for Google's script to load before calling initialize.
$.get('http://localhost/ajax_send_key.php',function (data){
const script = document.body.appendChild(document.createElement('script'));
script.src = `https://maps.googleapis.com/maps/api/js?key=${data}&libraries=places`;
script.addEventListener('load', initialize);
});

How to display multiple colour pins on Google Maps

I am currently displaying markers on a Google Map successfully, but want to overlay a different set of markers in a different colour for something else but I'm a bit stuck on how to do it.
I am getting the data into the $markers array from a database as follows:
while($row = $result->fetch_row())
{
$rows[]=$row;
$markers[$key] = trim($row[12]).','.trim($row[13]).','.trim($row[10]).','.trim($row[9]).','.trim($row[8]).','.trim($row[4]).','.trim($row[6]).','.trim($row[3]);
$key = $key +1;
}
Where the $row[""] is the data from the database including lat and lon for the marker locations.
The magic then happens in here:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<?=$api_key?>">
</script>
<script type="text/javascript">
var map;
var marker = {};
function initialize() {
var mapOptions = {
center: { lat: 20.1788823, lng: 13.8262155},
zoom: 2
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var markers = [];
<?php
$counter = 0;
foreach ($markers as $index => $list){
$marker_details = explode(',',$list);
echo 'markers["m'.($index-1).'"] = {};'."\n";
echo "markers['m".($index-1)."'].lat = '".$marker_details[0]."';\n";
echo "markers['m".($index-1)."'].lon = '".$marker_details[1]."';\n";
$counter++;
}
?>
var totalMarkers = <?=$counter?>;
var i = 0;
var infowindow;
var contentString;
for (var i = 0; i<totalMarkers; i++){
contentString = '<div class="content">'+
'<h2 class="firstHeading">'+markers['m'+i].name+'</h2>'+
'<div class="bodyContent">'+
'<p>'+markers['m'+i].content+'</p>'+
'</div>'+
'</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker['c'+i] = new google.maps.Marker({
position: new google.maps.LatLng(markers['m'+i].lat,markers['m'+i].lon),
icon: {
url: "https://maps.google.com/mapfiles/ms/icons/red.png"
},
map: map,
title: markers['m'+i].name,
infowindow: infowindow
});
//console.log(markers['m'+i].lat+','+markers['m'+i].lon);
google.maps.event.addListener(marker['c'+i], 'click', function() {
for (var key in marker){
marker[key].infowindow.close();
}
this.infowindow.open(map, this);
});
}
}
function panMap(la,lo){
map.panTo(new google.maps.LatLng(la,lo));
}
function openMarker(mName){
//console.log(marker);
for (var key in marker){
marker[key].infowindow.close();
}
for (var key in marker){
if (marker[key].title.search(mName) != -1){
marker[key].infowindow.open(map,marker[key]);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And finally it is rendered with this:
<div id="map-canvas"></div>
I have tried reading the second set of data from another data into $markers2[$key] but I'm then stuck at what to do next, I've tried quite a few different things (too many to list here!) but it either fails to render the new markers of fails to render anything at all on the map.
Any pointers in the right direction would be helpful. I'm not too familiar with javascript unfortunately.
Ok, I found the problem, the issue was that I was creating another "new" map each time and needed to remove the additional instances of :
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
Now the additional markers with the new data display correctly.
Thanks for all the downvotes, it really does concentrate the mind on finding the solution yourself!

google.maps.places is undefined

I have a website that loads 3 seperate "views" of a location via Google Maps, Street and Places.
Please see my code below:
I have finally gotten Maps and Street view to work properly but am struggling a bit with this one.
I have a tab that displays the same as map but with places added.
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
<script type="text/javascript">
var myLattitude = <?php echo $data["lattitude"]; ?>;
var myLongitude = <?php echo $data["longitude"]; ?>;
var poiMap;
var infowindow;
function initializePoi() {
var poiCentre = new google.maps.LatLng(myLattitude, myLongitude);
poiMap = new google.maps.Map(document.getElementById('poi-canvas'), {
center: poiCentre,
zoom: 15
});
var request = {
location: poiCentre,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(poiMap);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: poiMap,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(poiMap, this);
});
}
Now This initializes properly but the console throws the following error:
TypeError: google.maps.places is undefined
I just want to know why I get this error, I like having clean errorless code.
The places do actually show up properly and everything.
You should add the option libraries=places in the Google API URL
In your case you should replace the following:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
With this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Look at the end of the src=""
Now, you have to use https instead of http.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Everything else is same as previous answer mentioned.
Since the top answer addresses the vanilla version, this is for those using google-maps-react:
add libraries: ['places'] to your GoogleMapReact Component:
<GoogleMapReact
bootstrapURLKeys={{ key: apiKey, libraries: ['places'] }}
...
/>
If you are using React.
import { Wrapper as MapsWrapper } from "#googlemaps/react-wrapper";
// Note libraries prop.
<MapsWrapper apiKey={'YOUR_API_KEY'} libraries={['places']}>
<ChildComponent />
</MapsWrapper>

Correct way to parse this JSON and use it with D3

I'm using random user generator to get the JSON data:
http://randomuser.me/
I make a call everytime I click a button, so the zip code I get in return I use it to do a geocoder in google maps API and get a latitude and longitude. Until that it has work very well but I don't know how to use it on Google Maps. I'm trying to create D3 circles and there are two ways to do this:
1.- Using the drawing shapes from Google Maps API:
https://developers.google.com/maps/documentation/javascript/shapes#circles
2.- Using the custom overlay from Google Maps API:
https://developers.google.com/maps/documentation/javascript/customoverlays
I need to do it with the overlay and draw the graphics with D3 like in this example:
http://bl.ocks.org/mbostock/899711
So my doubts are:
1.- How can I use D3 to use the latitude and longitude and load them? In the example they load JSON from the directory but here I'm using remote data. Should I considered a JSON parse or a String or any other?
2.- What is the correct way to write this as a clean code? And why?
Thank you in advance
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/d3.v3.js"></script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(16.4706001, -33.6728973),
zoom:3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="button">
<button id="loadbutton">Click to Load</button>
</div>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
script.js
var randomuserURL = 'http://api.randomuser.me/';
var myButton = document.getElementById('loadbutton');
myButton.onclick = loadAJAX;
var lat = '';
var lng = '';
var zipcode;
var geocoder = new google.maps.Geocoder();
function loadAJAX () {
$.ajax({
url: randomuserURL,
dataType: 'json',
success: function(data){
zipcode = data.results[0].user.location.zip;
latlng();
}
});
}
function latlng () {
geocoder.geocode( { 'address': zipcode}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
console.log('Latitude: ' + lat + ' Logitude: ' + lng);
}
You basically have everything you need.
There's no need to load a "local" file -- d3.json will take any URL as its first argument. The only problem you may run into are browser security restrictions. In that case JSONP may help.
If your code works for you, it should be fine. Honestly, you have so little code that it really doesn't matter.

Google Map API v3 - Ajax (Javascript + Jquery) GET issue

I am trying to make the map load markers - pulled in from an xml file. It currently does this perfectly. However I also want the map to reload new markers based upon the month passed through from a hyperlink.
When the 'global_month' variable is changed via hyperlink the ajax request fires and the 'data_array' should be repopulated with the new data based upon the date passed to the 'if' statement later on. However it reuses the 'data_array' contents, and doesn't fill it with new data.
I have tried resetting the 'global_month' via 'global_month = []' in the 'change_date_range' function, however - the array doesn't seem to be refilled. I have spent 3 hours trying to work out where I am going wrong, but cannot. Can anyone help? Also is there a more efficient way of doing this?
Thank you very much for you time!
/////////////////////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "driving_test_centers.xml",
dataType: "xml",
success: parseXml
});
});
var global_month = 6;
function refetch()
{
$.ajax({
type: "GET",
url: "driving_test_centers.xml",
dataType: "xml",
success: parseXml
});
};
var data_array = [];
var empty_holder;
var empty_month;
var info_date;
var address1;
var address2;
var town;
var county;
var postcode;
var lat;
var lon;
var male_pass_percentage1;
var male_pass_percentage;
var female_pass_percentage1;
var female_pass_percentage;
var the_new_date;
var infowindow;
var xml_contents;
function parseXml(xml)
{
$(xml).find("test_center").each(function() // look for all of the test centers
{
center_name = $(this).attr('name');
address1 = $(this).find('address1').text();
address2 = $(this).find('address2').text();
town = $(this).find('town').text();
county = $(this).find('county').text();
postcode = $(this).find('postcode').text();
lat = $(this).find('lat').text();
lon = $(this).find('lon').text();
$(this).find("date_info").each(function()
{
info_date = $(this).attr('date');
empty_month = $(this).find('month').text();
male_pass_percentage = $(this).find('male');
male_pass_percentage = male_pass_percentage.find('pass_percentage').text();
female_pass_percentage = $(this).find('female');
female_pass_percentage = female_pass_percentage.find('pass_percentage').text();
if(empty_month == global_month){
data_array.push([lat,lon,center_name,info_date,male_pass_percentage,female_pass_percentage]);
}
});
});
}
function change_date_range(the_new_date){
global_month = the_new_date;
refetch();
init();
};
</script>
<script>
function init() {
var options = {
zoom: 5,
center: new google.maps.LatLng(55.3781, -3.4360),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var places;
places = null;
var map = new google.maps.Map(document.getElementById('map'), options);
var bounds = new google.maps.LatLngBounds();
var places = data_array;
var temp_location;
for (var i = 0; i < places.length; i++) {
temp_location = new google.maps.LatLng(places[i][0], places[i][1])
// Adding the markers
var marker = new google.maps.Marker({
position: temp_location,
map: map,
title: places[i][2]
});
// Wrapping the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(i, marker) {
// Creating the event listener. It now has access to the values of
// i and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
// Check to see if we already have an InfoWindow
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Setting the content of the InfoWindow
infowindow.setContent(places[i][2] + "<br />" + global_month + "<br />" + places[i][3] + "<br /><br />Male: " + places[i][4] + "%<br />Female: " + places[i][5] + "%");
// Tying the InfoWindow to the marker
infowindow.open(map, marker);
});
})(i, marker);
// Extending the bounds object with each LatLng
bounds.extend(temp_location);
}
// Adjusting the map to new bounding box
map.fitBounds(bounds)
};
</script>
</head>
<body onload="init()">
<div id="map" style="width:800px;height:600px"></div>
click
</body>
</html>
/////////////////////////////////////////////////////////////
XML file (small part of):
http://tinypaste.com/198889bb
You're not clearing out the data_array array...you just continue to add to it. Why don't you add data_array = []; to the beginning of the parseXml function
edit: you should also clear the markers that are already placed...a good way to make that easy is that when you add markers, hold them in an array, then you can loop through it, setting the map attribute of each to null:
for (x=0;x<markers.length;x++) {markers[x].setMap(null);}

Categories