Map Center and Marker create based on text input - google-maps

I want to define the map center and marker based on the text input HTML
It is work when i put lat/long on input text, but i need to press enter to make it work, i expected it will work when the map load without press enter,
<a id="myloc" type="text">-7.3344454, 112.7898796</a>
<button onclick="w3Load()">Load The Map</button>
<div id="map"></div>
The Java script :
function initAutocomplete() {
var input11 = document.getElementById("myloc").value
var input23 = new google.maps.LatLng(input11);
//var input23 = new google.maps.LatLng(document.getElementById("pac-input").value;
var map = new google.maps.Map(document.getElementById('map'), {
//center: {lat: -33.8688, lng: 151.2195},
center: input23,
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('myloc');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
function mapLoad(){
document.getElementById("map").style.display = 'block';
google.maps.event.trigger(map, 'resize');
}
i expected it will work when the map load without press enter, because the lat long is generated automatically based on another input form

I get a javascript error with the code in your question: InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value. because input11 is null.
I believe what you want to do is:
make your element with id="myloc" an HTML <input> element (text) and set its value to your comma separated string of latitude,longitude coordinates.
<input id="myloc" type="text" value="-7.3344454, 112.7898796" />
parse the .value of that element to separate out the two numbers (the google.maps.LatLng object takes two numbers as arguments, not a comma separated string):
var input11 = document.getElementById("myloc").value
var coords = input11.split(",");
var input23 = new google.maps.LatLng(coords[0], coords[1]);
use the resulting google.maps.LatLng to initialize the center of your map and for the position of the marker:
var map = new google.maps.Map(document.getElementById('map'), {
center: input23,
zoom: 13,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
})
Putting it all together:
function initAutocomplete() {
var input11 = document.getElementById("myloc").value
var coords = input11.split(",");
var input23 = new google.maps.LatLng(coords[0], coords[1]);
var map = new google.maps.Map(document.getElementById('map'), {
center: input23,
zoom: 13,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
});
proof of concept fiddle
code snippet:
function initAutocomplete() {
var input11 = document.getElementById("myloc").value
var coords = input11.split(",");
var input23 = new google.maps.LatLng(coords[0], coords[1]);
var map = new google.maps.Map(document.getElementById('map'), {
center: input23,
zoom: 13,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
})
// Create the search box and link it to the UI element.
var input = document.getElementById('myloc');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<input id="myloc" type="text" value="-7.3344454, 112.7898796" />
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete" async defer></script>

Related

Trying to get the marker var out of the foreach loop for markerCluster to work, what is the easiest way of doing this?

I am trying to add MarkerClusters to my map, however my marker variable is within a function with a foreach loop used to retrieve Instagram API data, what is the best possible way to get MarkerClusters working?
I tried wrapping the initMap function around the setMarkers function, putting the markerCluster variable within the setMarkers function and within the foreach loop but it just keeps showing the markers (pictures in my case)
<script>
let coords = document.getElementById("places").innerHTML;
let parts = coords.split(",");
let finalResult = []
while (parts.length) {
let newArr = parts.splice(0, 3);
finalResult.push(newArr);
}
console.log(finalResult)
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: 52.9,
lng: 101.2
}
});
setMarkers(map);
}
function setMarkers(map) {
finalResult.forEach((place) => {
var image = {
url: place[0],
scaledSize: new google.maps.Size(64, 64),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(32, 32)
};
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
shape: shape
});
})
var markerCluster = new MarkerClusterer(map, marker,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
One option is to create the MarkerClusterer inside your setMarkers function, then add the markers to it individually as you create them with the .addMarker method.
function setMarkers(map) {
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
finalResult.forEach((place) => {
var image = {
url: place[0],
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
});
markerCluster.addMarker(marker);
});
proof of concept fiddle
code snippet:
let coords = document.getElementById("places").innerHTML;
let parts = coords.split(",");
let finalResult = []
while (parts.length) {
let newArr = parts.splice(0, 3);
finalResult.push(newArr);
}
console.log(finalResult)
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -38,
lng: 150
}
});
setMarkers(map);
}
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
finalResult.forEach((place) => {
var image = {
url: place[0],
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
bounds.extend(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
});
markerCluster.addMarker(marker);
map.fitBounds(bounds);
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="places" style="display:none">https://maps.google.com/mapfiles/ms/micons/blue.png,-31.563910,147.154312, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.718234,150.363181, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.727111,150.371124, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.848588,151.209834,https://maps.google.com/mapfiles/ms/micons/blue.png,-33.851702,151.216968,
https://maps.google.com/mapfiles/ms/micons/blue.png,-34.671264,150.863657, https://maps.google.com/mapfiles/ms/micons/blue.png,-35.304724,148.662905, https://maps.google.com/mapfiles/ms/micons/blue.png,-36.817685,175.699196,https://maps.google.com/mapfiles/ms/micons/blue.png,-36.828611,175.790222,
https://maps.google.com/mapfiles/ms/micons/blue.png,-37.750000,145.116667, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.759859,145.128708, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.765015,145.133858,https://maps.google.com/mapfiles/ms/micons/blue.png,-37.770104,145.143299,
https://maps.google.com/mapfiles/ms/micons/blue.png,-37.773700,145.145187, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.774785,145.137978, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.819616,144.968119, https://maps.google.com/mapfiles/ms/micons/blue.png,-38.330766,144.695692,
https://maps.google.com/mapfiles/ms/micons/blue.png,-39.927193,175.053218, https://maps.google.com/mapfiles/ms/micons/blue.png,-41.330162,174.865694, https://maps.google.com/mapfiles/ms/micons/blue.png,-42.734358,147.439506, https://maps.google.com/mapfiles/ms/micons/blue.png,-42.734358,147.501315,
https://maps.google.com/mapfiles/ms/micons/blue.png,-42.735258,147.438000, https://maps.google.com/mapfiles/ms/micons/blue.png,-43.999792,170.463352,
</div>

I want to display the google map only after the search is clicked

I need to display the Google Map after I have performed my search, but the search box should have autocomplete locations/places. The search box should have the autocomplete places while searching and when clicked on THEN the map should be displayed with the location accordingly.
Here is the code:
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key
&libraries=places&callback=initAutocomplete"
async defer></script>
And this is the other code:
<input id="pac-input" class="controls" type="text" placeholder="Search" >
<div id="map"></div>
One approach would be to set the visibility property of the <div id="map"></div> element to hidden in your CSS.
#map {
height: 100%;
visibility: hidden;
}
Then, at the end of your search box places_changed event handler, set the map element's visibility to visible:
document.getElementById('map').style.visibility = 'visible';
Also, in order to prevent the search box from going invisible as well, I would remove this line from your code:
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
Here is a JSBin with a working example.

Algolia and google filter results based on user position

Hi I am using Google maps alongside algolia where I have an index 'locations' with 'lat' and 'lng'.
I am getting user location and watching position, I am also displaying markers from database based on lng and lat however I want to add a bit to it:
So I have followed that link:
https://www.algolia.com/doc/guides/geo-search/geo-search-overview/
And came up with:
#extends('master') #section('title', 'Live Oldham')
#section('extrafiles')
<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50&language=en"></script>
<script type="text/javascript" src="{!! asset('js/homesearch.js') !!}"></script>
#endsection
#section('content')
<div id="map_canvas" style="height:600px;"></div>
#endsection
and js:
$(document).ready(function() {
var map;
function initializeMap(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(position) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
));
}
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition(position);
console.log(position);
}
function watchCurrentPosition(position) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position,
)
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}else{
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 100 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
var markers = [];
//alert("heelo");
var fitMapToMarkersAutomatically = true;
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
console.log(hit)
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
markers.push(marker);
}
// Automatically fit the map zoom and position to see the markers
if (fitMapToMarkersAutomatically) {
var mapBounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
mapBounds.extend(markers[i].getPosition());
}
map.fitBounds(mapBounds);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
algoliaHelper.setQueryParameter('aroundRadius', 5000).search(); // 5km Radius
});
However there are few problems with this that I don't know how to tackle:
When user is moving, it doesn't center the map on the marker.
At this moment marker jumps between location when user moves, I would like for the marker to dynamically move on the map when user moves.
I want to use algolia to dynamically set markers, so I want to show markers with 5km radius from user location, and dynamically add or remove markers that are outside it.
I can't help you much with those questions since it's mostly about how to use GMap JS lib and I'm not experienced with it. However, something else catched my eyes:
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
You should put your coordinates in the _geoloc field in order to be able to use the geo-search features. It looks like this:
_geoloc: {
lat: 40.639751,
lng: -73.778925
}

Custom Search box for Google map

I am developing web application using Google map JavaScript version. I need to add search box like Google Search box which is on Google map (like attached image). And I need to search custom places which are on my database.
If it is possible, how to do this?
This example adds a search box to a map, using the Google Place Autocomplete feature. People can enter geographical searches. The search box will return a pick list containing a mix of places and predicted search terms.
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Diplay different Marker in Google Maps API V3 based on PHP value

I have gotten to the point of passing a value from set of Markers created via PHP but I can not figure out how to create or implement the IF condition to show the Marker Image related to the Type value.
Code:
<script type="text/javascript">
var iconStar = new google.maps.MarkerImage("googleMarkers/star.png",
new google.maps.Size(32, 28),
new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var iconBlue = new google.maps.MarkerImage("images/mm_20_blue.png",
new google.maps.Size(12, 20),
new google.maps.Point(0,0),
new google.maps.Point(6, 20));
var iconRed = new google.maps.MarkerImage("images/mm_20_red.png",
new google.maps.Size(12, 20),
new google.maps.Point(6, 20),
new google.maps.Point(5, 1));
var iconYellow = new google.maps.MarkerImage("images/mm_20_yellow.png",
new google.maps.Size(12, 20),
new google.maps.Point(6, 20),
new google.maps.Point(5, 1));
iconType = [] = iconStar;
iconType["0"] = iconStar;
iconType["1"] = iconBlue;
iconType["2"] = iconRed;
iconType["3"] = iconYellow;
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info, type) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: iconType,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
// panTo puts you back to the original center - not good for zoomed in nav
// map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
}
});
<?php
do {
$name=$row_rsCity['DEALER'];
$lat=$row_rsCity['lat'];
$lon=$row_rsCity['lng'];
$desc=$row_rsCity['ADDRESS'];
$city=$row_rsCity['CITY'];
$state=$row_rsCity['STATE'];
$phone=$row_rsCity['PHONENUMBER'];
$type=$row_rsCity['DEALER_TYPE'];
echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc<br/>$city , $state<br />Phone: $phone',$type);\n");
} while ($row_rsCity = mysql_fetch_assoc($rsCity));
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
I'm close but I can't find similar examples online so looking for a little help in solving this issue.
Thanks!
When you call the function addMarker, you need to pass the type of icon (numeric) via the type in your function list.
Then when you are adding the marker. :
function addMarker(lat, lng, info, type) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: iconType[type],
map: map
});
Add in the numeric type to reference the correct icon in your icon array.......
I haven't ever done it this way before but I don't see why it wouldn't work.
If that doesn't work you may want to look at this example. :
Change individual markers in google maps directions api V3
Google Maps API v3: How do I dynamically change the marker icon?