Gmaps maps showing listings by Yellow pages - javascript

I have created the map using Gmaps.js and passed the location and near by places to it but its showing listings by yellowpages.ca whenever I click a place following picture explains the problem. I am new in Google maps api.
var map;
var loc;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333,
zoom:15,
});
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
lat=latlng.lat();
lng=latlng.lng();
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
icon:$('#mainPin').val().trim(),
});
loc=new google.maps.LatLng(latlng.lat(),latlng.lng());
}}});
});
function showplaces(place,urll){
map.removeMarkers();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
icon:$('#mainPin').val().trim(),
});
map.addLayer('places', {
location : loc,
radius : 500,
types : [place],
search: function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
map.addMarker({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
title : place.name,
icon:urll,
});
}
}
}
});
}
}
});
if(place=='shopping_mall')
{
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
icon:$('#mainPin').val().trim(),
});
map.addLayer('places', {
location : loc,
radius : 500,
types : ['shoe_store','store','department_store'],
search: function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
map.addMarker({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
title : place.name,
icon:urll,
});
}
}
}
});
}
}
});
}
else if(place=='movie_theater')
{
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
icon:$('#mainPin').val().trim(),
});
map.addLayer('places', {
location :loc,
radius : 500,
types : ['movie_theater','zoo','stadium','night_club'],
search: function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
map.addMarker({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
title : place.name,
icon:urll,
});
}
}
}
});
}
}
});
}
}

What you see there are the attributions, it's required to show them.
Of course it's not required to show them multiple times.
The issue is(you may call it bug, I would call it a bad implementation ... heaven knows why so many people use these 3rd-party maps-libraries which only introduce bugs instead of useful features).
The "bug": each time you call map.addLayer('places') a new instance of google.maps.places.PlacesService will be created. Each instance will print separate attributions.
Gmaps.js doesn't have options to:
define where the attributions will be placed
use a single instance of the placesService
My suggestion would be to give up this "library" .
When you can't do without it check at the begin of showplaces if there is an object map.singleLayers.places . When it does it is the placesService-instance. Use this instance for a nearbySearch instead of using map.addLayer('places') .

Related

variable in Jquery For Google Map

I have ajax success function like below
success: function(result) {
for (var i = 0; i < result['Result'].length; i++) {
if (result['Result'][i]['ClusterId'] == '2414040001') {
if (result['Result'][i]['UserLatitude'] != '' &&
result['Result'][i]['UserLatitude'] != null) {
window.UserLatitude = result['Result'][i][
'UserLatitude'
];
} else {
window.UserLatitude = '';
}
if (result['Result'][i]['UserLongitude'] != '' &&
result['Result'][i]['UserLongitude'] != null) {
window.UserLongitude = result['Result'][i][
'UserLongitude'
];
} else {
window.UserLongitude = '';
}
console.log("LAT:" + UserLatitude + "LONG:" +
UserLongitude);
}
}
const myLatLng = {
lat: UserLatitude,
lng: UserLongitude
};
console.log(myLatLng);
const map = new google.maps.Map(document.getElementById(
"googleMap"), {
zoom: 4,
center: myLatLng,
});
new google.maps.Marker({
position: {
lat: -33.890,
lng: 151.274
},
map,
title: "Hello World!",
});
}
I am getting latitude and longitude from remote server and want use it for Google Map.
Its working fine if I use const like below
const myLatLng = { lat: -33.890, lng: 151.274 };
but if I use variable for it, its giving me error like below
InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: not a number
I am not getting idea what is the problem and how I can solve it.
Thanks!
The response returned by the server might be string.Can you please try this code to parse the lat and long value to float lat and lng value using parseFloat() method from javascript.
// const myLatLng = { lat: UserLatitude, lng: UserLongitude };
// change above code to
const myLatLng = { lat: parseFloat(UserLatitude), lng: parseFloat(UserLongitude) };
console.log(myLatLng);
const map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 4,
center: myLatLng,
});
new google.maps.Marker({
position: {lat: -33.890, lng: 151.274},
map,
title: "Hello World!",
});

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

Getting marker info from markerclusterer

I have pushed markers into the a markerClusterer. When I click on the markerClusterer I want to display the info of the nmarkers in the cluster. However, when I use the getMarkers() method, it does not give me the info that I stored in marker, only data about the marker itself. Is there any way that I can implement this? https://codesandbox.io/s/joey-gmaps-c5kdf
const markerCluster = new MarkerClusterer(map, [],
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
google.maps.event.addListener(markerCluster, 'clusterclick', function (c) {
console.log('Number of managed markers in cluster: ' + c.getSize());
var m = c.getMarkers();
for (i in m) {
console.log(Object.values(m[i]));
console.log(m[i].getTitle());
console.log(m[i].toString());
}
var p = [];
for (var i = 0; i < m.length; i++) {
p.push(m[i]);
}
});
You can get your markers' information using getMarkers so there may be an issue somewhere in your code implementation that you haven't posted.
Try the following jsfiddle based off of Google's example.
JS code below:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -28.024,
lng: 140.887
}
});
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length],
title: location.lat.toString() + "," + location.lng.toString(),
myObj: { myKey: i }
});
});
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
google.maps.event.addListener(markerCluster, 'clusterclick', function(c) {
console.log('Number of managed markers in cluster: ' + c.getSize());
var m = c.getMarkers();
for (let i in m) {
console.log(m[i].getLabel());
console.log(m[i].getTitle());
console.log(m[i].myObj.myKey);
}
});
}
var locations = [{
lat: -31.563910,
lng: 147.154312
},
{
lat: -33.718234,
lng: 150.363181
},
{
lat: -33.727111,
lng: 150.371124
},
{
lat: -33.848588,
lng: 151.209834
},
{
lat: -33.851702,
lng: 151.216968
},
{
lat: -34.671264,
lng: 150.863657
},
{
lat: -35.304724,
lng: 148.662905
},
{
lat: -36.817685,
lng: 175.699196
},
{
lat: -36.828611,
lng: 175.790222
},
{
lat: -37.750000,
lng: 145.116667
},
{
lat: -37.759859,
lng: 145.128708
},
{
lat: -37.765015,
lng: 145.133858
},
{
lat: -37.770104,
lng: 145.143299
},
{
lat: -37.773700,
lng: 145.145187
},
{
lat: -37.774785,
lng: 145.137978
},
{
lat: -37.819616,
lng: 144.968119
},
{
lat: -38.330766,
lng: 144.695692
},
{
lat: -39.927193,
lng: 175.053218
},
{
lat: -41.330162,
lng: 174.865694
},
{
lat: -42.734358,
lng: 147.439506
},
{
lat: -42.734358,
lng: 147.501315
},
{
lat: -42.735258,
lng: 147.438000
},
{
lat: -43.999792,
lng: 170.463352
}
]
If e.g. you click on the blue cluster #3, you'll get the following output logged in the console:
Number of managed markers in cluster: 3
T
-42.734358,147.439506
U
-42.734358,147.501315
V
-42.735258,147.438
Edit: This error appears to be typescript related. There's a solution in related thread custom property with google marker in type script
Please try the code below:
for (var i = 0; i < features.length; i++) {
const marker2 = new google.maps.Marker({
position: features[i].position,
icon: icons[features[i].type].icon,
animation: google.maps.Animation.DROP,
map: map
});
marker2.set("customInfo", features[i].location);
console.log("Marker222223", marker2["customInfo"]);
markerCluster.addMarker(marker2);
}
Hope this helps!
While creating markers add object into marker so that each marker will have asociated object with it i.e. customInfo
var marker = new google.maps.Marker({
position: accident_LatLng,
title: accident_title,
map: map,
customInfo: object,
});
to Access marker object use below code. I have created custom array to store marker object.
var markers = cluster.getMarkers();
var markerCustom = [];
for (var i = 0; i < markers.length; i++) {
markerCustom.push(cluster.markers_[i].customInfo)
}
Hope this helps
Reference https://medium.com/#sunil.jadhav38/implementing-marker-clustering-is-angular-using-google-charts-6b62a33f3b61

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>

Google maps and asynchronous javascript

In my controller, I have this function to get the coordinates of an address:
function get_coor(city, callback)
{
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": city }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
var location = results[0].geometry.location;
callback(location.lat(), location.lng());
}
else
{
callback(); // callback for error
}
});
}
Doing this works fine and outputs the correct latitude:
get_coor('Amsterdam', function(lat, lng) {
console.log('here is my lat:' + lat);
});
I want to use these coordinates in my google map, so I made it like this:
get_coor('Amsterdam', function(lat, lng) {
$scope.map = {center: {latitude: lat, longitude: lng }, zoom: 4 };
$scope.options = {scrollwheel: false};
$scope.marker = {
coords: {
latitude: lat,
longitude: lng
},
show: false,
id: 0
};
$scope.windowOptions = {
visible: false
};
$scope.onClick = function() {
$scope.windowOptions.visible = !$scope.windowOptions.visible;
};
$scope.closeClick = function() {
$scope.windowOptions.visible = false;
};
});
The map is centered correctly, so $scope.map = {center: {latitude: lat, longitude: lng }, zoom: 4 }; seems to work fine, but the marker is placed on it's default location, not Amsterdam. When I view the source, the coordinates of the marker are the right coordinates.
My guess is that it has something to do with asynchronous javascript, but I'm very new to this... Anyone who can help?
UPDATE:
Refreshing the page puts the marker on the right position, but it persists on first load.
Since geocoder.geocode function executes asynchronously and ui-gmap-marker is a child directive, you should call $apply() explicitly in that case:
$scope.marker = {
coords: {
latitude: location.lat(),
longitude: location.lng()
},
title: 'Amsterdam',
show: true,
id: 1
};
$scope.$apply();
Working example
var appMaps = angular.module('appMaps', ['uiGmapgoogle-maps']);
appMaps.controller('mainCtrl', function ($scope, uiGmapGoogleMapApi, uiGmapIsReady) {
$scope.windowOptions = {
visible: false
};
$scope.onClick = function () {
$scope.windowOptions.visible = !$scope.windowOptions.visible;
};
$scope.closeClick = function () {
$scope.windowOptions.visible = false;
};
$scope.options = { scrollwheel: false };
$scope.map = { center: { latitude: 30, longitude: 0 }, zoom: 4 };
var resolveAddress = function (address, callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
var location = results[0].geometry.location;
callback(location);
}
else {
callback(null);
}
});
}
uiGmapGoogleMapApi.then(function (gapi) {
resolveAddress('Amsterdam', function (location) {
$scope.$apply(function () {
$scope.map.center = { latitude: location.lat(), longitude: location.lng() };
$scope.marker = {
coords: {
latitude: location.lat(),
longitude: location.lng()
},
title: 'Amsterdam',
show: true,
id: 1
};
});
});
});
});
.angular-google-map-container {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
<script src="https://code.angularjs.org/1.3.14/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
<script src="http://rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>
<div ng-app="appMaps" id="map_canvas" ng-controller="mainCtrl">
<ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="true" options="options" bounds="map.bounds">
<ui-gmap-marker idkey="marker.id" coords="marker.coords" options="marker.options" click="onClick()" events="marker.events" />
</ui-gmap-google-map>
</div>

Categories

Resources